forEach vs loop

JavaScript performance comparison

Test case created by

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var arr = [];
  for(var i = 0; i < 100000; i++) arr[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
arr.forEach(function(v){v;});
pending…
loop
for(var i = 0, l = arr.length; i < l; i++){arr[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.

1 Comment

Joe Shelby commented :

Kind of an apples-to-oranges comparison. This isn't showing that the forEach loop is necessarily more expensive because the forEach requires a function call, where in this particular case, the for loop avoids the function invocation. A better test would be:

var f = function(t) { t; };

for(var i = 0, l = arr.length; i < l; i++){f(arr[i]);}

If you can keep the contents of the for loop simple, then consider it. but if the contents get complex such that it would be better implemented in a function, then the forEach loop probably runs about equal and is certainly more readable.