字符串拼接实验

《高性能javscript》笔记第五章

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function init(type){
var str = "I'm a thirty-five character string",
strs = [],
newStr='',
appends = 50000;
switch (type) {
case 'join':
while(appends--){
strs[strs.length] = str;
}
newStr = strs.join("");
break;
case 'concat':
while(appends--){
strs[strs.length] = str;
}
newStr = String.prototype.concat.apply(newStr,strs);
break;
case 'general':
while(appends--){
newStr+= str;
}
break;
default:
break;
}
}


console.time("数组项合并join")
init('join');
console.timeEnd("数组项合并join")

console.time("数组项合并concat")
init('concat');
console.timeEnd("数组项合并concat")

console.time("字符串拼接")
init('general');
console.timeEnd("字符串拼接")

结论是在chrome下测试:
join的方式最慢,concat和普通的字符串拼接时长差不多.

1
2
3
数组项合并join: 18.087890625ms
数组项合并.html:43 数组项合并concat: 6.107666015625ms
数组项合并.html:47 字符串拼接: 5.457763671875ms

书中说的ie7对于普通字符串拼接的非常慢的方式在chrome下是不存在的