Fastest array loops in Javascript (v54)

Revision 54 of this benchmark created by Camilo Martin on


Preparation HTML

<script>
  // Populate the base array
  var arr = [];
  for( var i = 0; i < 1000; i++ ) {
    arr[i] = 'value' + i;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
For loop, i-- with strict comparison
for (var i = arr.length - 1; i !== -1; i--) {
    window.foo = arr[i];
}
ready
For loop, basic
for( var i = 0; i < arr.length; i++ ) {
    window.foo = arr[i];
}
ready
While loop, basic
var i=0;
while(i < arr.length) {
    window.foo = arr[i];
    i++;
}
ready
For loop, cached
for (var i = 0, len = arr.length; i < len; i++) {
    window.foo = arr[i];
}
ready
For loop, i--
for (var i = arr.length - 1; i >= 0; i--) {
    window.foo = arr[i];
}
ready
Do-while loop, i--
var i = arr.length - 1;
do
{
    window.foo = arr[i];
}
while (i--);
ready
Do-while loop, --i
var i = arr.length;
if (i > 0)
{
    do
    {
        window.foo = arr[i];
    }
    while (--i);
}
ready
Reverse loop with assignation as condition
for (var i = arr.length - 1, j; undefined !== (j = arr[i]); i--) {
    window.foo = j;
}
ready

Revisions

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