forEach vs. jQuery .each vs. for vs for..in (v17)

Revision 17 of this benchmark created by kows on


Description

This test compares speeds from ECMAscript5 (262) Array.prototype.forEach vs jQuery .each method and standard for..in, for methods.

Modified preparation code to make the last test case working. (But be carefull this test case will not work if your array contains any "false" values... So, discouraged)

real array size for dom (30)

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 arr = [],
      loop = 30;

  while (loop--) {
    arr[loop - 1] = loop;
  }

  var fn = function(x) {
      x = x;
      };

  var jQfn = function(i, v) {
      v = v;
      };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
each()
$.each(arr, jQfn);
ready
forEach()
arr.forEach(fn);
ready
for..in
for (var i in arr) {
  fn(arr[i]);
}
ready
for
for (var i = 0; i < arr.length; i++) {
  fn(arr[i]);
}
ready
for, caching length
for (var i = 0, len = arr.length; i < len; i++) {
  fn(arr[i]);
}
ready
assign in loop declaration
for (var i = 0, j; j = arr[i]; i++) {
  fn(j);
}
ready
Underscore
_.each(arr, jQfn);
ready
while
var i = 0;
while (i < arr.length) {
  fn(arr[i]);
  i++;
}
ready
for, caching length + call
for (var i = 0, len = arr.length; i < len; i++) {
  fn.call(null, arr[i]);
}
ready
for, not setting len variable
for (var i = arr.length; i > 0;) {
  fn(arr[--i]);
}
ready
while, counting down
var i = arr.length;
while (i > 0) {
  fn(arr[--i]);
}
ready
for loop countin' down and floutin' the rules
for (var i = arr.length; i > 0; fn(arr[--i])) {}
ready
while until undefined, pop
while (x = arr.pop()) {
  fn(x);
}
ready
while until undefined, shift
while (x = arr.shift()) {
  fn(x);
}
ready
while until undefined, pop, non-destructive
cop = arr.slice();
while (x = cop.pop()) {
  fn(x);
}
ready
while until undefined, counting up
i = 0;
while (x = arr[i++]) {
  fn(x);
}
ready
reduce
arr.reduce(function(_, n) { fn(n) }, null);
ready
recursive, closure
function doLoop() {
  fn(arr.pop());
  if (arr.length != 0) doLoop();
}
doLoop();
ready
recursive
function doLoop(a) {
  fn(a.pop());
  if (a.length != 0) doLoop(a);
}
doLoop(arr);
ready
dereference throws
function cfn(n) {
  n.valueOf;
  fn(n);
}

function doLoop(a) {
  cfn(a.pop());
  doLoop(a);
}
try { doLoop(arr, 0); } catch(e) {}
ready
underscore reduce
_.reduce(arr, function(_, n) { fn(n) }, null);
ready
while pop, non destructive 2
cop = [].concat(arr);
while (x = cop.pop()) {
  fn(x);
}
ready
while pop non destructive
cop = []
while (x = arr.pop()) {
  fn(x);
  cop.push(x);
}
ready
while pop non destructive index
cop = []
var i = 0;
while (x = arr.pop()) {
  fn(x);
  cop[i++] = x;
}
ready

Revisions

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