先上结果:
连接1次
| 使用方法 | 执行次数 | 连接耗时 |
|---|---|---|
| + | 1 | 0.069ms |
| concat | 1 | 0.114ms |
| Array.join | 1 | 0.149ms |
| 模板字符串 | 1 | 0.051ms |
连接100次
| 使用方法 | 执行次数 | 连接耗时 |
|---|---|---|
| + | 100 | 0.011ms |
| concat | 100 | 0.028ms |
| Array.join | 100 | 0.056ms |
| 模板字符串 | 100 | 0.012ms |
连接10000次
| 使用方法 | 执行次数 | 连接耗时 |
|---|---|---|
| + | 10000 | 1.770ms |
| concat | 10000 | 0.939ms |
| Array.join | 10000 | 4.608ms |
| 模板字符串 | 10000 | 0.743ms |
1000000
| 使用方法 | 执行次数 | 连接耗时 |
|---|---|---|
| + | 1000000 | 31.039ms |
| concat | 1000000 | 36.029ms |
| Array.join | 1000000 | 211.760ms |
| 模板字符串 | 1000000 | 25.440ms |
代码
function log(...args) {
console.log(...args);
}
function timeOut(times, name, func) {
console.time(name);
let i = 0;
while (i < times) {
func();
i++;
}
console.timeEnd(name);
}
const a = 'a';
const b = 'b';
const str1 = () => a + b;
const str2 = () => a.concat(b);
const str3 = () => [a, b].join();
const str4 = () => `${a}${b}`;
const link = (times) => {
log(`------- ${times} -------`);
timeOut(times, 'string + 连接', str1);
timeOut(times, 'string concat 方法', str2);
timeOut(times, 'array join 连接', str3);
timeOut(times, '模板字符串', str4);
}
link(1);
link(100);
link(10000);
link(1000000);复制代码
最后
以上就是暴躁红牛最近收集整理的关于JavaScript 字符串连接性能比较的全部内容,更多相关JavaScript内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复