For/for of/for in/forEach comparison

Benchmark created by Zach Peltzer on


Setup

function f(x) {
    return x*x/2;
  }
  
  var arr = new Array(1000);
  for (let i = 0; i < 1000; i++) {
    arr[i] = Math.random();
  }

Test runner

Ready to run.

Testing in
TestOps/sec
Normal for loop
for (var i = 0; i < arr.length; i++) {
  f(arr[i]);
}
ready
Normal for loop, length cached
var l = arr.length;
for (var i = 0; i < l; i++) {
  f(arr[i]);
}
ready
Reverse for loop
for (var i = arr.length-1; i >= 0; i--) {
  f(arr[i]);
}
ready
for...in loop
for (var i in arr) {
  f(arr[i]);
}
ready
for...of loop
for (var x of arr) {
  f(x);
}
ready
forEach loop
arr.forEach(f);
ready
Normal for loop, local index
for (let i = 0; i < arr.length; i++) {
  f(arr[i]);
}
ready
Normal for loop, compressed
for(var i=0;i<arr.length;i++)f(arr[i])
ready
Normal for loop, prefix increment
for (var i = 0; i < arr.length; ++i) {
  f(arr[i]);
}
ready

Revisions

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