for vs forEach (v232)

Revision 232 of this benchmark created by ktmud on


Description

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

Preparation HTML

<script>
  var i, values = [], sums = [];

  for (i = 0; i < 10000; i++) {
   values[i] = i;
  }

  var tools = {
    forEach: function forEach(items, fn, ctx) {
      ctx = arguments.length >= 3 ? ctx : undefined
      for (var i = 0, len = items.length; i < len; i++) {
        fn.call(ctx, i, items[i], items)
      }
    }
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
sums[0] = 0
values.forEach(function add(item, i) {
  sums[0] += item
})
ready
for loop, cached length
sums[1] = 0
for (var i = 0, len = values.length; i < len; i++) {
  sums[1] += values[i]
}
ready
for loop in a helper
values[2] = 0
tools.forEach(values, function(item, i) {
  values[2] += item
})
ready

Revisions

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