for vs forEach (v251)

Revision 251 of this benchmark created by - on


Description

Is it faster to use the native forEach or just loop with for?

Preparation HTML

<script>
  var i, values = [],
      sum = 0;
  for (i = 0; i < 10000; i++) {
   values[i] = i;
  }
  
  function add(val, key, arr) {
   sum += val;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
values.forEach(add);
ready
for loop, simple
for (var i = 0; i < values.length; i++) {
  if (add(values[i], i, values) === false)
    break;
}
ready
for loop, cached length
for (var i = 0, len = values.length; i < len; i++) {
  if (add(values[i], i, values) === false)
    break;
}
ready
Array prototype call
Array.prototype.forEach.call(values, add);
ready

Revisions

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