for vs forEach (v16)

Revision 16 of this benchmark created by RubaXa on


Description

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

Setup

var i, values = [],
        sum = 0;
    for (i = 0; i < 10000; i++) {
      values[i] = i;
    }
    
    function add(val) {
      val * 2;
    }
    
    function each(obj, fn, context) {
      for (var i = 0, n = obj.length; i < n; i++){
        fn.call(context, obj[i], i, obj);
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
values.forEach(add);
ready
for loop, reverse
for (i = values.length - 1; i >= 0; i--) {
  add(values[i]);
}
ready
for loop, reverse 2
for (i = values.length; i--;) {
  add(values[i]);
}
ready
forEach function
each(values, add);
ready

Revisions

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