for vs forEach

JavaScript performance comparison

Revision 232 of this test case created by ktmud

Preparation code

<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

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
for loop in a helper
values[2] = 0
tools.forEach(values, function(item, i) {
  values[2] += item
})
pending…
forEach
sums[0] = 0
values.forEach(function add(item, i) {
  sums[0] += item
})
pending…
for loop, cached length
sums[1] = 0
for (var i = 0, len = values.length; i < len; i++) {
  sums[1] += values[i]
}
pending…

Compare results of other browsers

Revisions

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

0 Comments