array.push() is slow
array.push() is slow
Came across this code in jQuery 1.2.3, when looking at performance in
my javascript code.
merge: function( first, second ) {
// We have to loop this way because IE & Opera overwrite the length
// expando of getElementsByTagName
// Also, we need to make sure that the correct elements are being
returned
// (IE returns comment nodes in a '*' query)
if ( jQuery.browser.msie ) {
for ( var i = 0; second[ i ]; i++ )
if ( second[ i ].nodeType != 8 )
first.push( second[ i ] );
} else
for ( var i = 0; second[ i ]; i++ )
first.push( second[ i ] );
return first;
},
The fact is that according to my preliminary tests the push function
is up to 30% slower in firefox and IE6 than using direct assignment,
ex.
first[first.length] = second[ i ];
instead of using
first.push( second[ i ] );
This could be big speedup for jQuery in some scenarios.
Paste the following code into jconsole.org to see the difference on
your browser.
for(var x=0;x<10;x++)
{
var d1 = new Date().getTime();
var a;
a = [];
for (var i = 0; i < 100000; i++)
a[i] = i;
var d2 = new Date().getTime();
var a;
a = [];
for (var i = 0; i < 100000; i++)
a.push(i);
var d3 = new Date().getTime();
var dd1 = d2-d1;
var dd2 = d3-d2;
print("run " + x);
print("-----------------");
print("using direct: " + dd1);
print("using push: " + dd2);
print("difference: %" + ((1-(dd1/dd2))*100) )
print("-----------------\n");
}
---------------------------
Regards
Arnaldur Hilmisson
Developer
www.dohop.com