After the question, the String.prototype extension shows, productively below the function call 10 times, I wondered why simply adding "use strict" to the String.prototype method improves performance 10 times. The explanation given by Bergi is too short and incomprehensible.

Why is there such a dramatic difference in performance between two almost identical methods, the only difference between which is only "use strict" at the beginning? Can you explain in more detail and with justification?

 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 

Translation of the question “ Why“ use strict ”10x in this example? " @Exebook .

    1 answer 1

    The "use strict" mode does not require this context to be an object . If you call a function for a non-object, this will remain that non-object.

    And on the contrary, in this strict mode this context is always first wrapped in an object if it is not yet an object. For example, (42).toString() first wraps 42 in a Number object, and then then calls Number.prototype.toString with a Number object in the context of this . In strict mode, the this context remains untouched and is simply called Number.prototype.toString with 42 in the context of this .

     (function() { console.log(typeof this); }).call(42); // 'object' (function() { 'use strict'; console.log(typeof this); }).call(42); // 'number' 

    In your case, the non-strict version of the mode spends a lot of time moving and unfolding the string primitive to String and back. On the other hand, strict mode directly works directly with the string primitive, which improves performance.

    Translation of the “ Why“ use strict ”answer performance 10x in this example? » @Mattias Buelens .