Javascript string instantiation faster than this example?

I need to concatenate a bunch of strings in Javascript, and I'm looking for the fastest way to do this. Suppose Javascript is to create a large XML file, which naturally consists of many small lines. So I came up with:

var sbuffer = []; for (var idx=0; idx<10000; idx=idx+1) { sbuffer.push('<xmltag>Data comes here... bla... </xmltag>'); } // Now we "send" it to the browser... alert(sbuffer.join(")); 

Ignore the loop or other "complex" code that builds the example.

My question is: for an unknown number of lines, do you have a faster algorithm / method / idea to combine many small lines into a huge one?

+7
performance javascript join
source share
7 answers

Line change:

sbuffer.push('Data comes here... bla... ');

to

sbuffer[sbuffer.length] = 'Data comes here... bla... ';

will give you a 5-50% increase in speed (depending on the browser, in IE - the gain will be the highest)

Sincerely.

+13
source share

Question string concatenation JavaScript has an accepted answer that refers to a very good comparison Performance of string concatenation .

Edit: I would think that you can improve performance a bit using the Duff device, as the article suggests.

+15
source share

I think you are very close to optimal. YMMV, greater speed is achieved or lost in the JavaScript engine of the host process (for example, in the browser).

+1
source share

I think pushing strings into an array and then concatenating the array is the fastest way to concatenate strings in JavaScript. In this discussion of the W3C DOM vs. innerHTML has some supporting evidence. Notice the difference between innerHTML 1 and innerHTML 2.

+1
source share

As far as I know, your algorithm is good and known as a decisive solution to the string concatenation problem.

+1
source share

Beware of the bad IE garbage collector! What do you think should be done with your array after use? Probably he will get GC'd?

You can get perfornace when concatenating with joins, and then lose after GC. On the other hand, if you leave the array in scope all the time and DO NOT reuse it, this might be a good solution.

Personally, I need a simple solution: just use the + = operator.

0
source share

You can get a bit more buffering speed.

0
source share

All Articles