Most efficient way to concatenate strings in JavaScript?

omega picture omega · May 22, 2013 · Viewed 128.8k times · Source

In JavaScript, I have a loop that has many iterations, and in each iteration, I am creating a huge string with many += operators. Is there a more efficient way to create a string? I was thinking about creating a dynamic array where I keep adding strings to it and then do a join. Can anyone explain and give an example of the fastest way to do this?

Answer

Jakub Hampl picture Jakub Hampl · May 22, 2013

Seems based on benchmarks at JSPerf that using += is the fastest method, though not necessarily in every browser.

For building strings in the DOM, it seems to be better to concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.

(Thanks @zAlbee for correction)