1 min read

String concatenation or array join, which is faster?

Was working on a front end project that used JavaScript. I had written a simple string concatenation for a method. Later in a code review we had a discussion with my co-worker and friend regarding if the concatenation could be done using join instead. The thing is that JavaScript is a weird language. It is actually faster to use concatenation rather than array join.

String concatenation is when you have two or more strings and add them together. Like below:

var my_string = "H" + "e" + "l" + "l" + "o" + "!";

Another way to do this will be using individual statements such as below:

var my_string = 'H';
my_string += 'e';
my_string += 'l';
my_string += 'l';
my_string += 'o';
my_string += '!';

So an array join would

var arr = ['H', 'e', 'l', 'l', 'o', '!'];
var foo = arr.join('');

Although in other languages array joining might be quick due to how new browsers handle concatenation array joins are slower.

Google’s V8 engine handles concatenations in a special way. It has a special string-builder library in runtime/string-builder.h (https://code.google.com/p/v8/source/browse/trunk).

StringBuilderConcat creates an array with a pre-defined length. The C++ code is really optimized.

Firefox, Opera and IE has also optimized the string concatenation. It is such that any join for an array with unknown length will always be slower than concatenation.

Testing will show concatenation with all new browses are %20 faster than join. Which is kind of awesome.

Have fun!