Array.forEach vs. for-loop

JavaScript performance comparison

Test case created by Chris Blazek

Preparation code

<script>
  var arr = [0,1,2,3,4,5,6,7,8,9];
 
  var arr2 = arr.slice();
 
  for (var j = 0; j < 500; j++) {
   arr2.push(Math.round(Math.random()));
  }
 
  var arr3 = arr2.slice();
 
  for (var m = 0; m < 5000; m++) {
   arr3.push(Math.round(Math.random()));
  }
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
small array: native forEach
arr.forEach(function(v, i, a) {
 v;
});
pending…
small array: native for-loop
for (var i = 0, len = arr.length, v; i < len; i++) {
 v = arr[i];
}
pending…
medium array: native forEach
arr2.forEach(function(v, i, a) {
 v;
});
pending…
medium array: native for-loop
for (var i = 0, len = arr2.length, v; i < len; i++) {
 v = arr2[i];
}
pending…
large array: native forEach
arr3.forEach(function(v, i, a) {
 v;
});
pending…
large array: native for-loop
for (var i = 0, len = arr3.length, v; i < len; i++) {
 v = arr3[i];
}
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment