views:

161

answers:

2

I've read that if I have a for loop, I should not use string concation because it's slow. Such as:

for (i=0;i<10000000;i++) {
    str += 'a';
}

And instead, I should use Array.join(), since it's much faster:

var tmp = [];
for (i=0;i<10000000;i++) {
    tmp.push('a');
}
var str = tmp.join('');

However, I have also read that string concatention is ONLY a problem for Internet Explorer and that browsers such as Safari/Chrome, which use Webkit, actually perform FASTER is using string concatention than Array.join().

I've attempting to find a performance comparison between all major browser of string concatenation vs Array.join() and haven't been able to find one.

As such, what is faster and more efficient JavaScript code? Using string concatenation or Array.join()?

+1  A: 

My feeling is that since there's no "nice" way to do a feature check to see whether string concatenation is slow, and because Array.join() is not terrible in non-IE browsers, using the array approach is good because your pages will behave pretty well everywhere and you won't have a mess to maintain (and you can avoid browser sniffing).

Now if you're implementing a framework or a library and not just a feature or two on a site, then more fine tuning might be called for.

Finally, I suggest going back to google and reading some of the results you get from a search for "javascript string concatenation performance." I found several good ones and I only got through half the first SRP. Read the comments on the blog posts too because often you pick up interesting links there.

Pointy
+3  A: 

It appears Array.join() for the most part across browsers is faster.

Current gen Browsers

FF3        array.join is ~2x faster
Safari 3   array.join ~1.5x faster
Opera 9    += ~3x faster
ie6     array.join ~6x faster
ie7     array.join ~4x faster

Next gen browsers

FF3.1      += array.join equal in speed
Chrome     +=  ~1.25x faster
IE8     array.join ~1.6x faster
Webkit     array.join ~2x faster

Test results here: http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

NickNick
Actual times would be helpful here - if Opera is 50x faster than ie6 at joining strings, then whether joining or concatenating on Opera is faster doesn't really matter, since it probably won't be a bottleneck on that browser.
BlueRaja - Danny Pflughoeft