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?
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)
Look into the linked page. Seems like there is little difference between
+=
and doing a join on an array.It seems adding it into the DOM for every string is
66%
(For IE9) faster than creating a string out it and then adding the string to the DOM.the linked page uses += for both tests, no .join() in sight, so it's a meaningless test that only shows noise as any "difference". good example of how noisy js can be though... dom is slower than string, so use it sparingly.
Time is but one component. For iterative routines, I wonder what the impact to GC is between the various methods?
For large strings, array.join may be preferable due to string concat's very unpleasant memory bug bugs.chromium.org/p/v8/issues/detail?id=3175