为什么"使用严格的“;在本例中性能提高了10倍
Why "use strict" improves performance 10x in this example?
关于扩展String.prototype性能的问题,我真的很感兴趣,因为仅仅将"use strict"
添加到String.prototype
方法中,性能就提高了10倍。bergi的解释很简短,并没有向我解释。为什么两种几乎相同的方法之间有如此巨大的差异,只是顶部的"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
在严格模式下,this
上下文不会被强制为对象。如果你在一个非对象上调用一个函数,那么this
就是那个非对象。
相反,在非严格模式中,如果对象还不是对象,则this
上下文总是首先包装在对象中。例如,(42).toString()
首先将42
封装在Number
对象中,然后使用Number
对象作为this
上下文来调用Number.prototype.toString
。在严格模式下,this
上下文保持不变,只调用Number.prototype.toString
,42
作为this
上下文。
(function() {
console.log(typeof this);
}).call(42); // 'object'
(function() {
'use strict';
console.log(typeof this);
}).call(42); // 'number'
在您的情况下,非严格模式版本会花费大量时间将原始string
包装和展开为String
对象包装器并返回。另一方面,严格模式版本直接在基元string
上工作,这提高了性能。
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- 提高JQuery的性能
- 在Windows 10中自动执行例行程序(主要与浏览器交互)
- 使用正则表达式评估电子邮件地址时出现性能问题
- 如何处理10页以上的静态页眉/页脚
- React:按键的性能提升
- 在Three.js中导出网格会提高性能吗
- $(document).height()在刷新时随机化值(Safari 5.1.10)
- 在javascript中搜索项目列表的性能
- 为什么在许多浏览器中drawImage()的性能略好于createPattern()
- 为什么LZMA-JS压缩的字符串的大小比压缩前大大约10倍
- 提高 HTML5 Canvas 中 10,000 个粒子的性能
- 100+ 列和 10 行渲染性能在 UI-grid 中非常差
- 为什么用 InnerText 替换 InnerHTML 会导致性能下降 >15 倍
- 向10万用户添加cookie时需要考虑的性能问题
- 当添加超过10个系列时,Highcharts会降低性能
- Angular 2 RC 5 Internet Explorer 10的滚动性能很差
- WebView加载URL的速度比手机慢10倍's Chrome浏览器
- 为什么"使用严格的“;在本例中性能提高了10倍
- 扩展 String.prototype 性能表明函数调用速度提高了 10 倍