hur*_*lad 64 javascript string performance templates ecmascript-6
有人做过基准吗?我很好奇,如果使用字符串连接或使用Node和现代浏览器中的模板文字,HTML生成代码更快.
例如:
字符串连接
"<body>"+
"<article>"+
"<time datetime='" + date.toISOString() +"'>"+ date +"</time>"+
"</article>"+
"</body>"
Run Code Online (Sandbox Code Playgroud)
模板文字
`<body>
<article>
<time datetime='${ date.toISOString() }'>${ date }</time>
</article>
</body>`
Run Code Online (Sandbox Code Playgroud)
And*_*dri 71
目前看来字符串连接速度更快:http://jsperf.com/es6-string-literals-vs-string-concatenation
ES6 with variable 19,992,512 ±5.21% 78% slower
String concatenation with variable 89,791,408 ±2.15% fastest
ES6 with function 461,358 ±3.12% 99% slower
String concatenation with function 503,255 ±1.77% 99% slower
Run Code Online (Sandbox Code Playgroud)
我测试的是在Chrome 43.0.2334.0 canary(64位)上运行,它使用V8 4.3.31,并#enable-javascript-harmony启用了标志.
作为参考,Node.js上的最新版本(撰写本文时为0.12.0)使用的是V8 3.28.73:https://raw.githubusercontent.com/joyent/node/master/ChangeLog
我确信所有可能应用的性能优化尚未应用,因此当ES6接近完成并且这些功能迁移到稳定分支时,期望性能变得更好是合理的.
编辑:感谢评论@ user1329482,@ icl7126,Nicolai Borisik和FesterCluck.现在,自从提出这个问题已经过去了大约2年,ES6浏览器支持已经大大增加,并且已经进行了大量的性能优化.以下是一些更新:
在Chrome中(截至59.0.3035),ES6字符串文字更快:
ES6 with variable 48,161,401 ±1.07% fastest
String concatenation with variable 27,046,298 ±0.48% 44% slower
ES6 with function 820,441 ±1.10% 98% slower
String concatenation with function 807,088 ±1.08% 98% slower
Run Code Online (Sandbox Code Playgroud)
在Firefox(截至57.0.0)中,ES6字符串文字更快:
ES6 with variable 1,924,610,984 ±0.50% fastest
String concatenation with variable 1,876,993,458 ±0.79% 3% slower
ES6 with function 539,762 ±5.04% 100% slower
String concatenation with function 546,030 ±5.88% 100% slower
Run Code Online (Sandbox Code Playgroud)
在Safari(截至11.0.2)中,它取决于:
ES6 with variable 1,382,752,744 ±0.71% fastest
String concatenation with variable 1,355,512,037 ±0.70% 2% slower
ES6 with function 876,516 ±1.01% 100% slower
String concatenation with function 883,370 ±0.79% 100% slower
Run Code Online (Sandbox Code Playgroud)
使用类型转换字符串时,ES6字符串文字更快.但是,从文字中调用函数时,在此示例中字符串连接更快.
如果你真的想要深入并且需要从Safari中挤出每一滴性能,我建议设置测试,以查看在文字效果性能中是否/如何错误地键入变量和多个引用.
我在node.js v6.0.0上进行了一次天真的测试,并获得了几乎相同的性能.由于测试太天真,不要太相信数字.但是现在JIT编译器似乎生成了非常优化的代码.这让我决定更喜欢模板而不是连接我的节点应用程序.
作为参考,这是我使用的代码:
'use strict'
function strConcat(i) {
return 'abc' + i + 'def'
}
function strTemplate(i) {
return `abc${i}def`
}
function run(strategy) {
let before = new Date().getTime()
let len = 0
for ( let i = 0; i < 10000000; i+=1 ) {
len += strategy(i).length
}
console.log(len + ' - ' + ((new Date().getTime()) - before) + 'ms')
}
console.log('strConcat')
run(strConcat)
console.log('strTemplate')
run(strTemplate)
Run Code Online (Sandbox Code Playgroud)
输出是:
strConcat
128888890 - 1904ms
strTemplate
128888890 - 1979ms
Run Code Online (Sandbox Code Playgroud)
我曾经len绝对确保优化器不会优化整个循环.无论如何,它仍然是一个非常简单的测试.也许有人可以做一个更复杂的.