for vs forEach

JavaScript performance comparison

Revision 162 of this test case created by Joey Schooley

Preparation code

<script>
  var values = [];
  var sum = 0;
  for (var i = 0; i < 10000; i++) {
   values[i] = i;
  }
</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
forEach
values.forEach(function (val) {
   sum += val;
});
pending…
for loop, uncached length
for (var j = 0; j < values.length; j++) {
 sum += values[j];
}
pending…
for loop, cached length
for (var j = 0, l = values.length; j < l; j++) {
 sum += values[j];
}
pending…
for loop, reverse, cached length, iteration statement
for (var l = values.length - 1; l >= 0; l--) {
 sum += values[l];
}
pending…
for loop, reverse, cached length, no iteration statementmal reverse
for (var l = values.length; l--;) {
 sum += values[l];
}
pending…
for in
for (var j in values) {
 sum += values[j];
}
pending…
while loop, cached length
var l = values.length;
while (l--) {
 sum += values[l];
}
pending…
while loop, cached length, no code block
var l = values.length;
while (l-- && (sum += values[l]));
pending…
for loop, cached length, no code block (minimalist)
for (var l = values.length; l-- && (sum += values[l]););
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