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

Yot*_*tam 52 javascript string concatenation node.js

我明白做的事情就像

var a = "hello";
a += " world";
Run Code Online (Sandbox Code Playgroud)

它是相对非常慢的,因为浏览器会这样做O(n).没有安装新库,有没有更快的方法?

Azo*_*ous 39

这是在javascript中将字符串连接在一起的最快方法.

有关详细信息,请参阅:

为什么字符串连接比数组连接更快?

JavaScript:如何连接/组合两个数组以连接成一个数组?


Mus*_*afa 17

问题已经得到解答,但是当我第一次看到它时,我想到了NodeJS Buffer.但它比+更慢,所以很可能在字符串中没有任何东西比+更快.

使用以下代码进行测试:

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.");
Run Code Online (Sandbox Code Playgroud)

输出:

Normal took: 4 ms.
Buffer took: 458 ms.
Run Code Online (Sandbox Code Playgroud)

  • 使用该缓冲区,您正在初始化一个包含字符串的包装器,然后您将从2个包装器构建一个数组,通过该数组循环连接函数,(并且可能使用`+`来连接字符串),并返回它.我认为这解释了为什么缓冲区很慢. (2认同)

Cer*_*rus 8

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

库通常比本机JavaScript慢,尤其是在字符串连接或数字操作等基本操作上.

简单地说:+是最快的.