63

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?

Prince John Wesley
  • 60,780
  • 12
  • 83
  • 92
Yotam
  • 8,667
  • 13
  • 43
  • 66
  • 6
    Even if that would be true (that concatenation of strings is very slow), does your code depends on it so heavily that it even matters? – WTK Dec 13 '12 at 12:17

2 Answers2

29

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.
gilbertbw
  • 614
  • 2
  • 9
  • 27
Mustafa
  • 9,441
  • 8
  • 66
  • 116
  • 2
    With that buffer, you're initializing a wrapper containing a string, then you're building a array from the 2 wrappers, having the concatenate function loop through the array, (And probably use `+` to concatenate the strings), and return it. I think that explains why the buffer is slow. – Cerbrus Dec 14 '12 at 08:48
  • This test does not capture the intent to concatenate a high number of strings together in linear algorithmic time complexity. – Dico Aug 03 '20 at 19:53
16

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.

Cerbrus
  • 65,559
  • 18
  • 128
  • 140