When writing a javascript function that returns a string built from pieces of other strings, I was wondering which was faster: Build it directly to a string or push it on an array that will be joined on return.
I wrote a little test script and tried it in Firefox 2, Opera 9 and IE7. Opera was very fast and did the string concatenate in only 0.2s. Firefox took returned after 4.1s. After 20 minutes Internet Explorer 7 still hadn’t returned!!!
This made me curios so I had to do some more testing. The result was a little surprising.
With strings Firefox was up to 17 times slower than Opera depending on the size of the data. I had to stop measuring on IE after it was more than 700 times slower than Opera.
With arrays that are joined on return Opera was the fastest one up to a certain point, then it was surprisingly IE who was the fastest one. On the largest data IE returned after only 3 seconds, FF come second with 18s and at last OP on 25s!
Below you find the results of my measurements and the javascript code used.
Chars | Times | IE7 string | OP9 string | FF2 string | IE7 array | OP9 array | FF2 array |
---|---|---|---|---|---|---|---|
4000 | 1000 | 16 | 0 | 0 | |||
2000 | 500 | 16 | 0 | 0 | |||
20000 | 5000 | 78 | 0 | 0 | |||
40000 | 10000 | 16 | 0 | 47 | |||
200000 | 50000 | 4766 | 31 | 47 | |||
240000 | 60000 | 6437 | 31 | 47 | |||
320000 | 80000 | 21758 | 31 | 266 | |||
400000 | 100000 | 31 | 250 | 313 | 157 | 407 | |
800000 | 200000 | 78 | 766 | 656 | 297 | 1250 | |
1200000 | 300000 | 140 | 1579 | 984 | 485 | 2203 | |
1600000 | 400000 | 187 | 2672 | 1281 | 641 | 3703 | |
2000000 | 500000 | 235 | 4172 | 1593 | 812 | 5265 | |
2400000 | 600000 | 2813 | 5828 | 1938 | 3688 | 7234 | |
2800000 | 700000 | 6734 | 7781 | 2266 | 8000 | 9313 | |
3200000 | 800000 | 11203 | 10016 | 2547 | 12906 | 12235 | |
3600000 | 900000 | 16234 | 12624 | 2922 | 18671 | 15016 | |
4000000 | 1000000 | 21813 | 15281 | 3204 | 24969 | 18250 |
// Javascript
function test_array(size) {
var s=[];
for (var i=0; i < size; ++i) { s.push("TEST");}
return s.join("");
}
function test_string(size) {
var s="";
for (var i=0; i < size; ++i) { s += "TEST";}
return s;
}
function timer(func,size) {
var start = new Date().getTime();
return func(size).length + ": " + (new Date().getTime() - start );
}
var i=100000;
alert(i + " " + timer(test_array,i));
i+=100000; alert(i + " " + timer(test_array,i));
i+=100000; alert(i + " " + timer(test_array,i));