forEach vs loop

JavaScript performance comparison

Test case created by

Preparation code

Benchmark.prototype.setup = function() {
  var arr = [];
  for(var i = 0; i < 100000; i++) arr[i]=i;


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(var i = 0, l = arr.length; i < l; i++){arr[i];}

Compare results of other browsers


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.