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 .