Organizational Research By

Surprising Reserch Topic

fast way to concatenate strings in nodejs javascript


fast way to concatenate strings in nodejs javascript  using -'javascript,string,node.js,concatenation'

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?
    

asked Sep 18, 2015 by dhananjayksharma
0 votes
16 views



Related Hot Questions

3 Answers

0 votes

This is the fastest way known to join strings together in javascript.

For more details, see:

Why is string concatenation faster than array join?

JavaScript: How to join / combine two arrays to concatenate into one array?

answered Sep 18, 2015 by vickeykumar66
0 votes

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.

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.
answered Sep 18, 2015 by devkumargupta
0 votes

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

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

Simply put: + is the fastest.

answered Sep 18, 2015 by dhananjayksharma

...