Georgi
Georgi

Reputation: 4411

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?

Upvotes: 7

Views: 9046

Answers (7)

Sam Hasler
Sam Hasler

Reputation: 12616

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.

Upvotes: 15

Andrew Hedges
Andrew Hedges

Reputation: 21796

You might get a little more speed by buffering.

Upvotes: 0

Thevs
Thevs

Reputation: 3253

Beware of IE bad garbage collector! What do you suppose to do with your array after using? Probably it will get GC'd?

You can gain perfornace on concatenating with joins, and then lose on post-GC'ing. On the other hand if you leave an array in scope all the time, and NOT reuse it, that can be a good solution.

Personally I'd like the simpliest solution: just to use += operator.

Upvotes: 0

Sergey Ilinsky
Sergey Ilinsky

Reputation: 31535

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.

Upvotes: 13

Barth
Barth

Reputation: 15715

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

Upvotes: 1

John Topley
John Topley

Reputation: 115322

I think that pushing the strings onto an array and then joining the array is the fastest technique for string concatenation in JavaScript. There is some supporting evidence in this discussion about W3C DOM vs. innerHTML. Note the difference between the innerHTML 1 and innerHTML 2 results.

Upvotes: 1

Tomalak
Tomalak

Reputation: 338148

I think you are quite close to the optimum. YMMV, a great deal of speed is gained or lost within the JavaScript engine of the host process (e.g. browser).

Upvotes: 1

Related Questions