Different kinds of loop (v5)

Revision 5 of this benchmark created on


Description

In this revision I've updated the tests to call a function rather than count++; which is then not used.

I did this as in theory it's possible that some browsers will be able to see this variable is unused and optimise out that code so it's never run.

A real world app is unlikely to contain unused code, so this could skew the tests. - Jamie Mason / @GotNoSugarBaby

Preparation HTML

<script>
  var arr = [],
      obj = {};

  (function() {
    for (var i = 0; i < 1000; i++) {
      arr[i] = 'value' + i;
      obj[i] = 'value' + i;
    }
  }());

  function someFn(ix) {
    return ix * 5 + 1 / 3 * 8;
  }

  function forEachIterator(value, i, arr) {
    someFn(i);
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
arr.forEach
if ('forEach' in arr) {
  arr.forEach(function(value, i, arr) {
    someFn(i);
  });
} else {
  // i'm not testing shims
  for (var i = 0; i < arr.length; i++) {
    someFn(i);
  }
}
ready
var i in arr
for (var i in arr) {
  someFn(i);
}
ready
var i in arr (with hasOwnProperty check)
for (var i in arr) {
  if (!arr.hasOwnProperty(i)) continue;
  someFn(i);
}
ready
var i in obj
for (var i in obj) {
  someFn(i);
}
ready
var i in obj (with hasOwnProperty check)
for (var i in obj) {
  if (!obj.hasOwnProperty(i)) continue;
  someFn(i);
}
ready
for i < arr.length (without caching)
for (var i = 0; i < arr.length; i++) {
  someFn(i);
}
ready
for i < arr.length (with caching)
for (var i = 0, max = arr.length; i < max; i++) {
  someFn(i);
}
ready
for, counting down
for (var i = arr.length; i > 0; i--) {
  someFn(i);
}
ready
while i < arr.length (without caching)
var i = 0;
do {
  someFn(i);
  i++;
}
while (i < arr.length);
ready
while i < arr.length (with caching)
var i = 0,
    max = arr.length;
do {
  someFn(i);
  i++;
}
while (i < max);
ready
while, counting down
var i = arr.length;
do {
  someFn(i);
  i--;
}
while (i > 0);
ready
while, counting down (2)
var i = arr.length - 1;
do {
  someFn(i);
}
while (i--);
ready
while, counting down (3)
var i = arr.length;
if (i > 0) {
  do {
    someFn(i);
  }
  while (--i); // i must be greater than 0 here
}
ready
arr.forEach (cached iterator)
if ('forEach' in arr) {
  arr.forEach(forEachIterator);
} else {
  // i'm not testing shims
  for (var i = 0; i < arr.length; i++) {
    someFn(i);
  }
}
ready

Revisions

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