Underscore.each vs jQuery.each vs. for loop vs. forEach (v99)

Revision 99 of this benchmark created on


Description

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

Preparation HTML

<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>

Test runner

Ready to run.

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

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.