Fastest array loops in Javascript (v505)

Revision 505 of this benchmark created on


Setup

var arr = [];
  for (var i = 0; i < 1000; i++) arr[i] = i;
  
  function someFn(a) {};

Test runner

Ready to run.

Testing in
TestOps/sec
For loop, basic
for (var i = 0; i < arr.length; i++) {
  someFn(arr[i]);
}
ready
For loop, basic, preinc
for (var i = 0; i < arr.length; ++i) {
  someFn(arr[i]);
}
ready
While loop, basic
var i = 0;
while (i < arr.length) {
  someFn(arr[i++]);
}
ready
For loop, cached
for (var i = 0, len = arr.length; i < len; i++) {
  someFn(arr[i]);
}
ready
For loop, dec
for (var i = arr.length - 1; i >= 0; i--) {
  someFn(arr[i]);
}
ready
Do-while loop, --i
var i = arr.length;
if (i)
  do {
    someFn(arr[--i]);
  } while (i);
ready
shift()
var temp = [];
var value;
while (value = arr.shift()) {
  someFn(value);
  temp.push(value);
}

arr = temp;
ready
pop()
var temp = [];
var value;
while (value = arr.pop()) {
  someFn(value);
  temp.push(value);
}

arr = temp;
ready
forEach
arr.forEach(function(v) {
  someFn(v)
})
ready
forEach direct
arr.forEach(someFn);
ready

Revisions

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