nodejs的字符串文字(‘’)和模板文字(``)性能比较
js支持两种方式定义字符串:
- 使用
''
const str = "Hello " + "world!";
- 使用
``
const worldText = "world!"
const str = `Hello ${worldText}`;
我们可能不会太关注这些,应该都是怎么习惯怎么来,本文就对这两种方式进行性能测试(此次测试只针对node,对于browser或者其他环境可能存在差异),来看看具体有什么不同:
基准测试
我们使用for循环(分别测试10次 , 100次, 1000次, 1000000次)来增长字符串,看看具体表现是怎么样的:
字符串文字(''):
const iterations = ITERATION_TOTAL // 10, 100, 10000, 1000000
const stringText = 'string'
let text = 'text'
const start = performance.now()
for (let i = 0; i < iterations; i++) {
// 只连接一个字符
text += stringText;
// 连接两个字符
// text = stringText + " text " + stringText
}
const end = performance.now()
console.log(`耗时 ${end - start} ms.`);
模板文字(``):
const iterations = ITERATION_TOTAL // 10, 100, 10000, 1000000
const stringText = 'string'
let text = `text`
const start = performance.now()
for (let i = 0; i < iterations; i++) {
// 只连接一个字符
text = `text${stringText}`;
// 连接两个字符
// text = `${stringText} text ${stringText}`;
}
const end = performance.now()
console.log(`耗时 ${end - start} ms.`);
这次的测试在 Node Js v18.17.0 上使用不同的循环迭代运行了测试:10、100、10000、100000 和 1000000。并统计了每次迭代的平均时间。
结果
10次:

100次:

10000次:
100000次:
1000000次:

结论
在简单、数量较小的遍历循环中,字符串文字和模板文字的写法耗时虽然略有不同,但是基本相差无几,使用哪种方式都一样。但是在处理大型数据集时,复杂的算法、生成非常长的字符串、或者vue和react使用需要大量迭代和频繁重新渲染的组件来说,使用字符串文字(' ')是更好的选择。


















