ultimate-concat-vs-join

JavaScript performance comparison

Test case created by Remy Sharp

Info

Real world use of string concatenation proven to be very slow in Webkit based browsers. Note that for the sake of the browser, I've reduced the loop down from 100,000 iterations to 1,000 iterations.

Full detail of problem shown in this Opera article by Erik Möller.

Here is my follow up comment, suggesting that although Webkit, and Chrome in particular claim to have string concatenation licked, it's still a problem and can only be solved (for this real world problem) by using array joins.

Update - I'm no longer convinced the concat is the issue, though switching to the array solves the problem:

Damn, after almost being able to sleep on this, I more and more think the problem isn't the concat, but the index lookup - which is what's been already discussed. Obviously the array provides the solution because it has the native index support - whereas swapping data[i] out for data.substr(i, 1) yields almost exactly the same results ref.

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
concat
// Hotspot testing. Backreference copy.
var dest = 'apple';
var start = new Date();
while (dest.length < 1000) {
 var offs = dest.length - 5;
 for (var i = offs; i < offs + 10; ++i)
 dest += dest[i];
}
pending…
join
// Hotspot testing. Backreference copy.
var dest = 'apple'.split(''); // turn it in to an array
var start = new Date();
while (dest.length < 1000) {
 var offs = dest.length - 5;
 for (var i = offs; i < offs + 10; ++i)
 dest.push(dest[i]); // push on to the array, instead of concat
}
dest = dest.join('');
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

14 comments

ruiespinho commented :

done

vic commented :

done :)

Mario commented :

And- done!

Shrikant Thakare commented :

Done.Awesome ! Thanks for sharing.

Ryan Parman commented :

Tested Firefox 4.0.1, Chrome 12 (latest dev channel), latest WebKit nightly (as Safari 5.0.5), and iOS 4.3.3 on an iPhone 4. Hopefully this helps! :)

Jeroen commented :

There she blows... Opera 11.50

Isaac commented :

Interesting benchmark. Tested FF4, C12, O11.5 and iOS4.3.3. Hope that helps =) Will be interested to hear your conclusions so make sure to tweet them !

seb commented :

done Safari 5.0.5

erika commented :

Done:)

Craig Patik commented :

Given the disparity between browsers (some way better at concat, some better at join), is one method supposed to be better in theory? i.e., did some of the vendors screw up, or did others just choose to optimize one particular routine?

galambalazs commented :

This benchmark is wrong on so many levels...

Jesse commented :

IE7, you are one odd ball.

Add a comment