I read this article at Usable Type and said to myself – true, true, true, true, WTF?
So I did a quick test:
- Concatenating 3 long strings: without ~135ms (45ms) [25ms] {33ms}, with ~220ms (120ms) [40ms] {65ms}
- Concatenating 12 shorter strings: without ~215ms (190ms) [85ms] {90ms}, with ~470ms (180ms) [105ms] {165ms}
The tests were done on my laptop on Windows Vista in Firefox (IE7) [Safari3] {Opera 9.2}, the function was repeated 10000 times. It seems that you’re better off without using array.join(), though it might be an option for huge joins in IE.
I wonder what sparked the idea – I’ve seen the use of arrays for string operations in Flash – string.split(old).join(new) for replacing until a proper method was available. I’ve never thought about abusing JavaScript that way…
On a side note – have you noticed that Firefox was significantly slower than others?
Update: I created a test page so you can test your browsers and post a comment…
Concatenating three long strings through array.join() was definitely the fastest for me. It was the only test (of the four) that had times of less than 1000 ms. Some were even down to 400 ms. On the other hand the slowest was 12 shorter strings using array.join().
Regular concatenation was about the same in both cases.
FF2 on Windows XP with P4 3.2 GHz (the hyper-threading kind).
YMMV.
[…] A number of people have mentioned to me that the Array.join technique for string concatenation is a bad one, particularly if you’re only doing it with a small number of strings. Our benchmarks show it being faster for IE when you get to about 6/7 string concatenations, so it’s been useful to us in some situations. But I’d agree with Stuart below that for the average situation it’s not going to be worth it. However, I don’t see using Array.join() for string concatenation as an abuse of JavaScript. […]
Using Array.join vs. the += operator made a huge difference in IE6. Your tests are also on a fairly small number of elements, The idea of array.join was that it might make sense on very large datasets.
I think we can all agree that Array.join makes sense on a huge number of elements (more than 20) and only in IE.
[…] Update: A number of people have mentioned to me that the Array.join technique for string concatenation is a bad one, particularly if you’re only doing it with a small number of strings. Our benchmarks show it being faster for IE when you get to about 6/7 string concatenations, so it’s been useful to us in some situations. But I’d agree with Stuart below that for the average situation it’s not going to be worth it. However, I don’t see using Array.join() for string concatenation as an abuse of JavaScript. […]