Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript String concatenation faster than this example?

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?

like image 336
Georgi Avatar asked Sep 30 '08 14:09

Georgi


2 Answers

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.

like image 62
Sam Hasler Avatar answered Oct 05 '22 11:10

Sam Hasler


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.

like image 30
Sergey Ilinsky Avatar answered Oct 05 '22 12:10

Sergey Ilinsky