Category Archives: just fun

John Roach

December 17, 2014

Wow… It has been quite an adventure. 101 posts since the start of my blog. I had started this blog waaay back in 2008 as a Blogspot site. Later on upgraded to self hosted site. Haven’t looked back since.

Thank you for reading!

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:

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

So an array join would

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!