Warm tip: This article is reproduced from serverfault.com, please click

Most efficient way to concatenate strings in JavaScript?

发布于 2013-05-22 16:08:42

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?

Questioner
omega
Viewed
0
Jakub Hampl 2018-04-24 17:20:00

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)