Following the question Extending String.prototype performance I am really intrigued, because just adding "use strict"
to a String.prototype
method improved performance 10 times. The explanation by bergi is short and does not explain it to me. Why there is such a dramatic difference between two almost identical methods, that only differ in "use strict"
at the top? Can you explain in more detail and with the theory behind this?
String.prototype.count = function(char) {
var n = 0;
for (var i = 0; i < this.length; i++)
if (this[i] == char) n++;
return n;
};
String.prototype.count_strict = function(char) {
"use strict";
var n = 0;
for (var i = 0; i < this.length; i++)
if (this[i] == char) n++;
return n;
};
// Here is how I measued speed, using Node.js 6.1.0
var STR = '0110101110010110100111010011101010101111110001010110010101011101101010101010111111000';
var REP = 1e4;
console.time('proto');
for (var i = 0; i < REP; i++) STR.count('1');
console.timeEnd('proto');
console.time('proto-strict');
for (var i = 0; i < REP; i++) STR.count_strict('1');
console.timeEnd('proto-strict');
Result:
proto: 101 ms
proto-strict: 7.5 ms
this[i] === char
and see if you get the same difference?this[i] === char
in a DOM environment and the result is the samecount
function, thethis
parameter has to be cast to a string object instead of a string literal whereas in strict mode it does not have to in order to operate correctly. Why this is the case is beyond me, I'm very interested in the answer.this
, but in strict mode it skips that step, so you get the primitive string, or whatever was provided forthis
."use strict";
everywhere boys! Goooold