(fixed) for vs forEach vs while (v369)

Revision 369 of this benchmark created on


Description

Is it faster to use the native forEach or just loop with for? And how fast is while?

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
simple for
for (i = 0; i < values.length; i++) {
  add(values[i]);
}
ready
cached for
for (var i = 0, len = values.length; i < len; i++) {
  add(values[i]);
}
ready
cached for ++i
for (var i = 0, len = values.length; i < len; ++i) {
  add(values[i]);
}
ready
while
var i=0, len=values.length;
while (i<len) {
  add(values[i]);
  i++;
}
ready
while ++i
var i=0, len=values.length;
while (i<len) {
  add(values[i]);
  ++i;
}
ready

Revisions

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