for vs forEach

JavaScript performance comparison

Revision 427 of this test case created by

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
    var i, values = [],
        sum = 0;
    for (i = 0; i < 10000; i++) {
     values[i] = i;
    }
    
    function add(val) {
     sum += val;
    }
  
  function addIdxVal(idx, val) {
     sum += val;
  }
  
  function addIdx(idx){
  sum += values[idx];
  }

};
</script>

Preparation code output

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></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(add);
pending…
for loop, simple
for (var i = 0; i < values.length; i++) {
  add(values[i]);
}
pending…
for loop, cached length
var len = values.length;
for (var i = 0; i < len; i++) {
  add(values[i]);
}
pending…
for...of
for(var val of values){
   add(val);
}
pending…
angular.forEach
angular.forEach(values, add);
pending…
$.each - both
$.each(values, addIdxVal);
pending…
$.each - idx
$.each(values, addIdx);
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