for vs forEach (v120)

Revision 120 of this benchmark created 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) {
   sum += val;
  }

  function samEach1(arr, iterator) {
    for (i = 0; i < arr.length; i += 1) {
      iterator(arr[i]);
    }
  }

function samEach2(arr, iterator) {
    for (i = 0; i < arr.length; i++) {
      iterator(arr[i]);
    }
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
values.forEach(add);
ready
for loop, simple
for (i = 0; i < values.length; i++) {
 add(values[i]);
}
ready
each1
samEach1(values, add);
ready
each2
samEach2(values, add);
ready

Revisions

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