为什么在此示例中,“使用严格”可将性能提高 10 倍?
2022-08-30 04:32:54
在扩展String.prototype性能的问题之后,我真的很感兴趣,因为仅仅添加一种方法就可以将性能提高10倍。bergi的解释很短,没有向我解释。为什么两种几乎相同的方法之间存在如此巨大的差异,而这些方法仅在顶部有所不同?您能更详细地解释一下这背后的理论吗?"use strict"
String.prototype
"use strict"
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');
结果:
proto: 101 ms
proto-strict: 7.5 ms