Some quick benchmarking (each test = 500k appended elements and the results are averages of multiple runs) showed the following:
Firefox 3.6 (Mac):
- Small arrays:
arr[arr.length] = b
is faster (300ms vs. 800ms)
- Large arrays:
arr.push(b)
is faster (500ms vs. 900ms)
Safari 5.0 (Mac):
- Small arrays:
arr[arr.length] = b
is faster (90ms vs. 115ms)
- Large arrays:
arr[arr.length] = b
is faster (160ms vs. 185ms)
Google Chrome 6.0 (Mac):
- Small arrays: No significant difference (and Chrome is FAST! Only ~38ms !!)
- Large arrays: No significant difference (160ms)
I like the arr.push()
syntax better, but I think I'd be better off with the arr[arr.length]
Version, at least in raw speed. I'd love to see the results of an IE run though.
My benchmarking loops:
function arrpush_small() {
var arr1 = [];
for (a = 0; a < 100; a++)
{
arr1 = [];
for (i = 0; i < 5000; i++)
{
arr1.push('elem' + i);
}
}
}
function arrlen_small() {
var arr2 = [];
for (b = 0; b < 100; b++)
{
arr2 = [];
for (j = 0; j < 5000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}
}
function arrpush_large() {
var arr1 = [];
for (i = 0; i < 500000; i++)
{
arr1.push('elem' + i);
}
}
function arrlen_large() {
var arr2 = [];
for (j = 0; j < 500000; j++)
{
arr2[arr2.length] = 'elem' + j;
}
}