JavaScript 字符串连接性能比较

2,439 阅读1分钟

先上结果:

连接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);