The most efficient way to concatenate strings in JavaScript?

In JavaScript, I have a loop that has many iterations, and at each iteration I create a huge line with many += operators. Is there a more efficient way to create a string? I was thinking of creating a dynamic array, where I continue to add rows to it, and then make the connection. Can someone explain and give an example of the fastest way to do this?

+112
performance javascript string concatenation
May 22 '13 at 16:08
source share
4 answers

Using JSPerf- based , using += seems to be the fastest method, although not necessarily in every browser.

To build strings in the DOM, it seems best to first join the string and then add to the DOM, and then iteratively add this to the house. You must check your own case.

(Thanks @zAlbee for the fix)

+101
May 22 '13 at 16:16
source share

I have no comments on concatenation itself, but I would like to point out that @Jakub Hampl's suggestion:

To build strings in the DOM, in some cases it would be better to iteratively add the DOM and then add a huge string right away.

incorrect because it is based on an error test. This test is never added to the DOM.

This fixed test shows that creating a line immediately before rendering is much, MUCH faster. This is not even a competition.

(Sorry, this is a separate answer, but so far I do not have enough answers to comment on the answers.)

+55
Dec 15 '13 at 5:55
source share

Three years have passed since the answer to this question, but I will still give my answer :)

Actually, the accepted answer is not entirely correct. The Jakub test uses a hard-coded string that allows the JS engine to optimize code execution (Google V8 is really good at that!). But as soon as you use completely random strings ( here is JSPerf ), then string concatenation will be in second place.

+13
Mar 09 '16 at 17:32
source share

You can also make concat string with template literals . I updated JSPerf tests by other authors to include it.

 for (var res = '', i = 0; i < data.length; i++) { res = '${res}${data[i]}'; } 
0
Dec 07 '18 at 23:56
source share



All Articles