Comparing jQuery each function vs. javascript for loop for iterating through a large array.

We're assuming that the jQuery method would be measurably slower, as it must be a wrapper for a JavaScript loop function, thus only adding overhead. Maybe jQuery will surprise us!

// create test array with 100,000 elements
testArray = new Array();
for (i = 0; i < 100000; i++)
    testArray[i] = i;

   
//jQuery $.each
start = new Date().getMilliseconds();
    $.each(testArray, function(key, value) {
        dummy = key; // simple code, as we're more interested in the loop execution time itself, not the code within
    });   
stop = new Date().getMilliseconds();
jQueryExecutionTime = stop - start;

// vanilla for loop
start = new Date().getMilliseconds();
    arraySize = testArray.length;
    for(i = 0; i < arraySize; i++)
        dummy = i;
stop = new Date().getMilliseconds();
vanillaExecutionTime = stop - start;

// results
document.write('jQuery each: ' + jQueryExecutionTime + ' milliseconds<br />');
document.write('standard for loop: ' + vanillaExecutionTime + ' milliseconds');

 

Well, we got results we expected, but found that the fault doesn't lie with jQuery alone. The browser itself plays a much larger role in the execution time gap. See below.


Firefox 3.6
jQuery each: 71 milliseconds
standard for loop: 1 milliseconds

Safari 5.0.4
jQuery each: 3 milliseconds
standard for loop: 1 milliseconds

Chrome 5.0.4
jQuery each: 10 milliseconds
standard for loop: 2 milliseconds

IE 8.0
jQuery each: 78 milliseconds
standard for loop: 62 milliseconds

Internet Explorer closes the gap a little bit, but only to demonstrate how slowly it executes JavaScript in comparison to other browsers!

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *