Today, I read this thread about the speed of string concatenation.
Surprisingly, string concatenation was the winner:
The result was opposite of what I thought. Besides, there are many articles about this which explain oppositely like this.
I can guess that browsers are optimized to string concat on the latest version, but how do they do that? Can we say that it is better to use + when concatenating strings?
Update
So, in modern browsers string concatenation is optimized so using + signs is faster than using join when you want to concatenate strings.
But @Arthur pointed out that join is faster if you actually want to join strings with a separator.
Update – 2020
Chrome: Array join is almost 2 times faster is String concat +
See: https://stackoverflow.com/a/54970240/984471
As a note:
- Array
joinis better if you havelarge strings - If we need generate
several small stringsin final output, it is better to go with string concat+, as otherwise going with Array will need several Array to String conversions at the end which is performance overload.
The V8 javascript engine (used in Google Chrome) uses this code to do string concatenation:
So, internally they optimize it by creating an InternalArray (the
partsvariable), which is then filled. The StringBuilderConcat function is called with these parts. It’s fast because the StringBuilderConcat function is some heavily optimized C++ code. It’s too long to quote here, but search in the runtime.cc file forRUNTIME_FUNCTION(MaybeObject*, Runtime_StringBuilderConcat)to see the code.