for vs $.each vs. _.each

JavaScript performance comparison

Revision 16 of this test case created

Info

Testing the time it takes to loop an array using native vs for.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="//documentcloud.github.com/underscore/underscore-min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var array = new Array();
    for (var i = 0; i < 100000; i++) {
        array[i] = i;
    }
    var total;  // add them - prevent peep-hole optimizer from eliding the loop
   
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Native JS (for)
var l = array.length;
total = 0;
for (var i = 0; i < l; i++) {  
    total += array[i];  // prevent peep-hole optimizer from eliding the loop
}
 
pending…
$.each
total = 0;
$.each(array, function (i, elem) {  
    total += elem;
});
pending…
$(array).each
total = 0;
$(array).each(function (i, elem) {
    total += elem;
});
pending…
_.each
total = 0;
_.each(array, function (elem) {
    total += elem;
});
pending…
array.forEach()
total = 0;
array.forEach(function (elem) {
    total += elem;
});
pending…
array.reduce()
total = array.reduce(function (sum, elem) {
    return sum + elem;
}, 0);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment