使用传播参数连接字符串的最有效方法

Most efficient way to concatenate strings using spread arguments

我正在尝试寻找一种更好的方法来连接 javascript ES6 中的字符串。下面是当前的代码片段。

方法一:

function concat(...strings){
    return ''.concat(...strings);
}

方法二:

function concat(...strings){
    return strings.join('');
}

示例:

concat("Hey", "There", "How", "Are", "You"); // output is "HeyThereHowAreYou"

我不确定这些方法的性能,因为参数的数量可能会增加。任何评论都将不胜感激,这可能是最好的,或者任何其他方法都可以提供帮助。

字符串连接可以通过多种方式完成

  • 加号 (+) 运算符。 + 运算符在其操作数之一是字符串时立即进行字符串连接。然后将另一个操作数转换为字符串。示例:

    "Say hello " + 7 + " times fast!" ’Say hello 7 times fast!’

  • 或者,您可以使用 += where

    a += b

    的缩写

    a = a + b

  • 连接字符串数组。将要连接的字符串收集到一个数组中,然后加入它。

var arr = [];

 arr.push("Say hello ");

 arr.push(7);

 arr.push(" times fast");

 arr.join("")
’Say hello 7 times fast’

哪个更快?

字符串是不可变的,大多数结果为字符串的字符串操作都会产生新的字符串。

因此,诸如 C# 或 Java 之类的字符串处理类似于 JavaScript 的语言有特殊的 classes 可以帮助连接字符串。例如,C# 调用此 class StringBuilder。但是,现代 Java 脚本引擎在内部优化 + 运算符 1. Tom Schuster mentions Ropes 2 作为一种可能的优化技术。因此 JavaScript.

中不需要 StringBuilder

只需使用 += 即可完成。

参考文献:

“回复:String concatenation” – Brendan Eich 的电子邮件指出 + 在现代 Java 脚本引擎上更快。

Ropes: an Alternative to Strings (1995)”,作者:Hans-J。伯姆、拉斯·阿特金森、迈克尔·普拉斯。

ES5 方式:如果您不确定传递的 nos 参数,请在函数内部使用 arguments 对象。

function concat() {
  let str = '';
  for(let i=0; i < arguments.length; i++) {
    str += arguments[i];
  }
  return str;
}

var resultant_str = concat("Hey", "There", "How", "Are", "You");
console.log(resultant_str);

ES6方式:使用Rest params,将不定数量的参数表示为一个数组。

function concat(... theArgs) {
  return theArgs.reduce((prev, cur) => prev + cur);
}

var resultant_str = concat("Hey", "There", "How", "Are", "You");
console.log(resultant_str);

就性能而言,使用 for 循环要好得多,因为 reduce 需要递归调用的回调函数。缩写 here.

我建议使用 _.reduce。 之所以说它使用 += 一种围绕字符串数组的逻辑来连接,这是 perf 高效的 jsperf

片段:

    _.reduce(['x', 'y', 'z'], function(accumulator, currentItem) {
    return accumulator + currentItem;
});
// xyz

参考:

https://jsperf.com/concat-join-reduce