Jquery each vs Underscore each vs For loops (v47)

Revision 47 of this benchmark created on


Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js">
</script>
<script>
var arraysLength = [1000, 1, 10, 0, 100, 5, 500, 2000];
var arrays = [];
var expectedRet = 0;
arraysLength.forEach(function(length) {
        var array = [];
        for (var i = 0; i < length; ++i) {
                array.push({
                        n: i
                });
                expectedRet += i;
        };
        arrays.push(array);
});
var ret = 0
function oi(o, i) {
        ret += o.n;
}
function io(i, o) {
        ret += o.n;
}
function check() {
  var lastRet = ret;
        ret = 0;
        if (lastRet != expectedRet)
                throw new Error('Wrong ret: ' + lastRet + ', expected: ' + expectedRet);
}

var forEach = function(a, c) {
  var l = a.length;
  for (var i = 0; i < l; i++) c(a[i], i)
}
var forEac2 = function(a, c) {
  "use asm";
  var l = +a.length;
  for (var i = +0; i < l; i++) c(a[i], i)
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Jquery each
$.each(arrays, function(i, array) {
  $.each(array, io);
});
check();
ready
Underscore each
_.each(arrays, function(array) {
  _.each(array, oi);
});
check();
ready
For normal
for (var i = 0, l = arrays.length; i < l; i++) {
  var array = arrays[i];
  for (var j = 0, m = array.length; j < m; j++)
    oi(array[j], j);
};
check();
ready
For reversed
for (var i = arrays.length - 1; i >= 0; i--) {
  var array = arrays[i];
  for (var j = array.length - 1; j >= 0; j--)
    oi(array[j], j);
};
check();
ready
Native array forEach
arrays.forEach(function(array) {
  array.forEach(function(o, i) {
          ret += o.n;
  });
});
check();
ready
Native array forEach with Named function
arrays.forEach(function(array) {
  array.forEach(oi);
});
check();
ready
custom forEach
forEach(arrays, function(array) {
  forEach(array, oi);
});
check();
ready
custom forEach 2
function it(o, i) {
  ret += o.n;
}
forEach(arrays, function(array) {
  forEach(array, it);
});
check();
ready
custom forEach Named
forEach(arrays, function(array) {
  forEach(array, oi);
})
check();
ready
Jquery each Named
$.each(arrays, function(i, array) {
        $.each(array, io);
});
check();
ready
custom forEach asm.js Named
forEac2(arrays, function(array) {
  forEac2(array, oi);
})
check();
ready
custom forEach asm.js
function it(o, i) {
  ret += o.n;
}
forEac2(arrays, function(array) {
  forEac2(array, it);
})
check();
ready

Revisions

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