I have to concatenate a bunch of Strings in Javascript and am searching for the fastest way to do so. Let's assume that the Javascript has to create a large XML-"file" that, naturally, consists of many small Strings. 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(”));
Do not pay any attention to the loop or the other "sophisticated" code which builds the example.
My question is: For an unknown number of Strings, do you have a faster algorithm / method / idea to concatenate many small Strings to a huge one?
The question JavaScript string concatenation has an accepted answer that links to a very good comparison of JavaScript string concatenation performance.
Edit: I would have thought that you could eek out a little more performance by using Duff's device as the article suggests.
Changing the line:
sbuffer.push(‘Data comes here... bla... ’);
to
sbuffer[sbuffer.length] = ‘Data comes here... bla... ’;
will give you 5-50% speed gain (depending on browser, in IE - gain will be highest)
Regards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With