for vs forEach

JavaScript performance comparison

Revision 642 of this test case created by

Preparation code

<script>
  var values = [],
      sum = 0;
  for (i = 0; i < 10000; i++) {
   values[i] = Math.random();
  }
  
  function add(val) {
   sum += val;
  }
</script>
      
<script>
Benchmark.prototype.setup = function() {
  sum = 0;

};

Benchmark.prototype.teardown = function() {
  sum = 0;

};
</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 ... in
for (let val in values) {
 add(val);
}
pending…
for loop, cached length
for (let i = 0, len = values.length; i < len; ++i) {
 add(values[i]);
}
pending…
forEach
values.forEach(add);
pending…
for loop, reverse
for (let i = values.length - 1; i--;) {
 add(values[i]);
}
pending…
for loop, simple
for (let i = 0; i < values.length; ++i) {
 add(values[i]);
}
pending…
forEach (arrow)
values.forEach(val => add(val));
pending…
for...of
for (let val of values) {
 add(val);
}
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