Underscore.each vs jQuery.each vs. for loop vs. forEach

JavaScript performance comparison

Revision 99 of this test case created

Info

All test assume you want to do something with the loop index, the relative item in the array, and the resulting array.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="//documentcloud.github.com/underscore/underscore-min.js">
</script>
<script>
  var pi = Math.PI,
      a = new Array(1000000),
      o,
      e,
      r;

var f_each = function(a, fn) {
    for (var i = 0, l = a.length; i < l; i++) {
        fn(a[i], i);
    }
    return a;
}


</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
jQuery.each
r = $.each(a, function(i, it) {
  o = it;
  e = pi + i;
  a[i] = e;
});
pending…
good old for loop
for (var item, i = 0, len = a.length; i < len; i++) {
  o = a[i]
  e = pi + i;
  a[i] = e;
};
r = a;
pending…
underscore.each
_.each(a, function(it, i) {
  o = it;
  e = pi + i;
  a[i] = e;
});
r = a;
pending…
good old for loop (decrementing)
var i = a.length;
for (; i > 0; i--) {
  o = a[i]
  e = pi + i;
  a[i] = e;
};
r = a;
pending…
forEach
a.forEach(function(it, i) {
  it = a[i]
  e = pi + i;
  a[i] = e;
});
r = a;
pending…
functional
r = f_each(a, function(it, i) {
    o = it;
    e = pi + i;
    a[i] = e;
});
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