ome*_*ega 147 javascript string performance concatenation
在JavaScript中,我有一个循环,有许多迭代,并在每次迭代中,我创建一个包含许多+=
运算符的巨大字符串.有没有更有效的方法来创建一个字符串?我正在考虑创建一个动态数组,我不断添加字符串,然后进行连接.任何人都可以解释并举例说明最快的方法吗?
我想知道为什么String.prototype.concat
没有得到任何爱。在我的测试中(假设您已经有一个字符串数组),它优于所有其他方法。
测试代码:
const numStrings = 100;
const strings = [...new Array(numStrings)].map(() => Math.random().toString(36).substring(6));
const concatReduce = (strs) => strs.reduce((a, b) => a + b);
const concatLoop = (strs) => {
let result = ''
for (let i = 0; i < strings.length; i++) {
result += strings[i];
}
return result;
}
// Case 1: 52,570 ops/s
concatLoop(strings);
// Case 2: 96,450 ops/s
concatReduce(strings)
// Case 3: 138,020 ops/s
strings.join('')
// Case 4: 169,520 ops/s
''.concat(...strings)
Run Code Online (Sandbox Code Playgroud)
您也可以使用模板文字进行字符串连接。我更新了其他发布者的JSPerf测试以包括其中。
for (var res = '', i = 0; i < data.length; i++) {
res = `${res}${data[i]}`;
}
Run Code Online (Sandbox Code Playgroud)
我在 node 和 chrome 中都做了一个快速测试,发现在这两种情况下+=
都更快:
var profile = func => {
var start = new Date();
for (var i = 0; i < 10000000; i++) func('test');
console.log(new Date() - start);
}
profile(x => "testtesttesttesttest");
profile(x => `${x}${x}${x}${x}${x}`);
profile(x => x + x + x + x + x );
profile(x => { var s = x; s += x; s += x; s += x; s += x; return s; });
profile(x => [x, x, x, x, x].join(""));
profile(x => { var a = [x]; a.push(x); a.push(x); a.push(x); a.push(x); return a.join(""); });
Run Code Online (Sandbox Code Playgroud)
结果节点:7.0.10
chrome 86.0.4240.198 的结果:
归档时间: |
|
查看次数: |
115188 次 |
最近记录: |