Fastest array loops in Javascript

JavaScript performance comparison

Revision 295 of this test case created by jason

Preparation code

<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

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

Compare results of other browsers

Revisions

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

0 Comments