for vs forEach vs while (v81)

Revision 81 of this benchmark created by PhilT on


Description

Compare for, forEach and while.

  • for in is not compared as it's recommended to avoid it
  • Lengths are always cached
  • Always called with a function (to avoid skewing results)

This version tries to simplify tests.

Preparation HTML

<script>
  var i, values = [],
      sum = 0;
  for (i = 0; i < 10000; i++) {
    values[i] = i;
  }

  function add(val) {
    sum += val;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
values.forEach(add);
ready
for
var len = values.length;
for (i = 0; i < len; i++) {
  add(values[i]);
}
ready
while
i = 0;
len = values.length
while (i < len) {
  add(values[i]);
  i += 1;
}
ready
for, inline
var len = values.length;
for (i = 0; i < len; i++) {
  sum += values[i];
}
ready
while, inline
i = 0;
len = values.length
while (i < len) {
  sum += values[i];
  i += 1;
}
ready

Revisions

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