看不同的插件代码,看到不一样的字符串拼接方式,
(1)
很多是['str1', 'str2'].join('')
搞的,(2)
也有一些是 ‘+’ 直接拼接的,具体到我自己写的时候,我也是什么都写过,(3)
用反斜杠 ‘\’都写过,后来用 eslinter后发现,它不建议这么写,说是以后的规范(eg: ES6等)可能不支持这种写法了,(4)
也发现还可以用反撇号 ` 包起来,哎,总之很多种…
High-performance String Concatenation in JavaScript
Do you wanna test it?
The first uses the string concatenation operator:
// standard string append
var str = "";
for (var i = 30000; i > 0; i--) {
str += "String concatenation. ";
}
The second uses an array join:
// array join
var str = "", sArr = [];
for (var i = 30000; i > 0; i--) {
sArr[i] = "String concatenation. ";
}
str = sArr.join("");
The truth is rather more complex.
- Chrome 6.0: standard string appends are usually quicker than array joins, but both complete in less than 10ms.
- Opera 10.6: again, standard appends are quicker, but the difference is marginal—often 15ms compared to 17ms for an array join.
- Firefox 3.6: the browser normally takes around 30ms for either method. Array joins usually have the edge, but only by a few milliseconds.
- IE 8.0: a standard append requires 30ms, whereas an array join is more than double—typically 70ms.
- Safari 5.0.1: bizarrely, a standard append takes no more than 5ms but an array join is more than ten times slower at 55ms.
- IE7: If you’re supporting IE7,
array joins
remain the best method for concatenating a large number of strings.