Fastest array loops in Javascript (v283)

Revision 283 of this benchmark created on


Preparation HTML

<script>

</script>

Setup

// Populate the base array
    var arr = [];
    for (var i = 0; i < 1000; i++) {
      arr[i] = 'value' + i;
    }
  
    function someFn(ix) {
      acc += ix * 5 + 1 / 3 * 8;
    }
  
  var len = arr.length
    , i = 0
    , acc = 0;

Teardown



            console.log(acc);
        
  

Test runner

Ready to run.

Testing in
TestOps/sec
For loop, basic
for (i = 0; i < arr.length; i++) {
  someFn(i);
}
ready
While loop, basic
while (i < arr.length) {
  someFn(i);
  i++;
}
ready
For loop, cached
for (i = 0, len = arr.length; i < len; ++i) {
  someFn(i);
}
ready
For loop, i--
for (i = arr.length; i > 0; i--) {
  someFn(i);
}
ready
Do-while loop, i--
i = arr.length - 1;
do {
  someFn(i);
}
while (i--);
ready
Do-while loop, --i
i = arr.length;
if (i > 0) {
  do {
    someFn(i);
  }
  while (--i);
}
ready
For..in loop
for (var i in arr) {
  someFn(i);
}
ready
while loop i--
i = arr.length;
while (i--) {
  someFn(i);
}
ready
For loop, i -= 1
for (i = arr.length; i > 0; i -= 1) {
  someFn(i);
}
ready
For loop, i -= 1 II
for (i = arr.length; i > 0; i -= 1) {
  someFn(i);
}
ready
For loop
for (i = arr.length; i > 0; i--) {
  someFn(i);
}
ready
Fast
for (; i < len; ++i) {
  someFn(i);
}
ready
Fast?
for (; i < len; i++) {
  someFn(i);
}
ready

Revisions

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