在 nodeJS/JavaScript 中连接字符串的快速方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13859543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 14:58:17  来源:igfitidea点击:

Fast way to concatenate strings in nodeJS/JavaScript

javascriptstringnode.jsconcatenation

提问by Yotam

I understand that doing something like

我明白做类似的事情

var a = "hello";
a += " world";

It is relatively very slow, as the browser does that in O(n). Is there a faster way of doing so without installing new libraries?

它相对非常慢,因为浏览器在O(n). 在不安装新库的情况下,是否有更快的方法?

回答by Mustafa

The question is already answered, however when I first saw it I thought of NodeJS Buffer. But it is way slower than the +, so it is likely that nothing can be faster than + in string concetanation.

这个问题已经回答了,但是当我第一次看到它时,我想到了 NodeJS Buffer。但它比 + 慢得多,所以很可能没有比 + 在字符串合并中更快的了。

Tested with the following code:

使用以下代码进行测试:

function a(){
    var s = "hello";
    var p = "world";
    s = s + p;
    return s;
}

function b(){
    var s = new Buffer("hello");
    var p = new Buffer("world");
    s = Buffer.concat([s,p]);
    return s;
}

var times = 100000;

var t1 = new Date();
for( var i = 0; i < times; i++){
    a();
}

var t2 = new Date();
console.log("Normal took: " + (t2-t1) + " ms.");
for ( var i = 0; i < times; i++){
    b();
}

var t3 = new Date();

console.log("Buffer took: " + (t3-t2) + " ms.");

Output:

输出:

Normal took: 4 ms.
Buffer took: 458 ms.

回答by Cerbrus

There is not really any other way in JavaScript to concatenate strings.
You could theoretically use .concat(), but that's way slowerthan just +

JavaScript 中没有任何其他方法可以连接字符串。
理论上你可以使用.concat(),但这比仅仅+

Libraries are more often than not slower than native JavaScript, especially on basic operations like string concatenation, or numerical operations.

库通常比原生 JavaScript 慢,尤其是在字符串连接或数字运算等基本操作上。

Simply put: +is the fastest.

简单地说:+是最快的。

回答by Stuart Hallows

You asked about performance. See this perf testcomparing 'concat', '+' and 'join' - in short the + operator wins by far.

你问的是性能。请参阅比较“concat”、“+”和“join”的这个性能测试——简而言之,+ 运算符到目前为止获胜。