Ter*_*rry 7 javascript performance concatenation
是[x,y,z].join('')真的快于x + y + z字符串?
在join()更快的印象下,我开始使用我的代码而不是+,然后我在Google Analytics代码中遇到以下行:
ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
Run Code Online (Sandbox Code Playgroud)
假设谷歌的编码员是最知识渊博的人之一,这让我很奇怪.当然,该行仅在每页加载时运行一次,并且可以说任何速度差异都可以忽略不计.但是呢?
.join()用于连接字符串的Array 方法(-trick)的根源是当网站在Internet Explorer上运行时很多.对于IE6 + 7的非常真实的比.join()是多少比使用更快的+操作,由于一个非常糟糕的行为与IE的字符串操作.
对于其他浏览器而言,性能差异并不大,所以这是一个很好的建议.join()(再次,当时).如今,大多数引擎都会大量优化字符串操作,除非您认为任何代码在IE6 + 7中运行很多,否则您应该使用+.
使用以下代码在 Firefox 6.0.2 中使用 Firebug 控制台:
b = new Date().getTime(); for (var i = 0; i < 10000; i++) {a = "sfhfdshdshsdh" + "sfhsfdhsfhdsfh" + "shsfdsdgsdgsgsdfgdfsgsfdghsdfhsdh";} c = new Date().getTime(); d = c - b;
Run Code Online (Sandbox Code Playgroud)
和
b = new Date().getTime(); for (var i = 0; i < 10000; i++) {a = ["sfhfdshdshsdh","sfhsfdhsfhdsfh","shsfdsdgsdgsgsdfgdfsgsfdghsdfhsdh"].join();} c = new Date().getTime(); d = c - b;
Run Code Online (Sandbox Code Playgroud)
我的“+”平均在 40 左右,“join”平均在 50 左右,所以看来 join 速度较慢。这很可能是因为需要创建一个用于连接的数组。此外,在具有不同解释器的不同浏览器中,这可能会有所不同。
| 归档时间: |
|
| 查看次数: |
246 次 |
| 最近记录: |