Fastest array loops in Javascript (v295)

Revision 295 of this benchmark created by jason on


Preparation HTML

<script>
  // Populate the base array
  var arr = [];
  
  for (var i = 0; i < 1000; i++) {
    arr.push(i);
  }
var r=0;
  function someFn(ix) {
    r+=ix * 5 + 1 / 3 * 8;
    return r;
  }
  function postLoop() {
     return (r % 3==0) ? r: 1;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
For loop, basic
for (var i = 0; i < arr.length; i++) {
  someFn(arr[i]);
}postLoop();
ready
While loop, basic
var i = 0;
while (i < arr.length) {
  someFn(arr[i]);
  i++;
}postLoop();
ready
For loop, cached
for (var i = 0, len = arr.length; i < len; i++) {
  someFn(arr[i]);
}postLoop();
ready
For loop, i--
for (var i = arr.length; i > 0; i--) {
  someFn(arr[i]);
}postLoop();
ready
Do-while loop, i--
var i = arr.length - 1;
do {
  someFn(arr[i]);
}
while (i--);
postLoop();
ready
Do-while loop, --i
var i = arr.length;
if (i > 0) {
  do {
    someFn(arr[i]);
  }
  while (--i);
}postLoop();
ready
For..in loop
for (var i in arr) {
  someFn(arr[i]);
}
postLoop();
ready
Order
while( i = arr.shift() ) {
  someFn(i);
}
postLoop();
ready
forEach
arr.forEach(function (v){
  someFn(v)
});
ready
order validation
while( (i = arr.shift()) !== undefined ) {
  someFn(i);
}postLoop();
ready
While ! Undefined
var a;
while((a = arr[i++]) !== undefined) {
  someFn(a);
}postLoop();
ready
Pop
while( i = arr.pop() ) {
  someFn(i);
}postLoop();
ready
Order w/ array copy
var copy = arr.slice(0);
while( i = copy.shift() ) {
  someFn(i);
}postLoop();
ready
While length--
var l = arr.length;
while(l--) {
  someFn(arr[l]);
}postLoop();
ready
for decrement
var l = arr.length;
for(;l--;) {
  someFn(arr[l]);
}
postLoop();
ready
for decrement 1
for(var l = arr.length;l--;) {
  someFn(arr[l]);
}
postLoop();
ready

Revisions

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