Fastest array loops in Javascript

JavaScript performance comparison

Revision 159 of this test case created

Preparation code

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

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
For loop, basic
for (var i = 0; i < arr.length; i++) {
  var num = 1 + 1;
}
pending…
While loop, basic
var i = 0;
while (i < arr.length) {
  var num = 1 + 1;
  i++;
}
pending…
For loop, cached
for (var i = 0, len = arr.length; i < len; i++) {
  var num = 1 + 1;
}
pending…
For loop, i--
for (var i = arr.length; i > 0; i--) {
  var num = 1 + 1;
}
pending…
Do-while loop, i--
var i = arr.length - 1;
do {
  var num = 1 + 1;
}
while (i--);
pending…
Do-while loop, --i
var i = arr.length;
if (i > 0) {
  do {
    var num = 1 + 1;
  }
  while (--i);
}
pending…
For..in loop
for (var i in arr) {
  var num = 1 + 1;
}
pending…
Order
while( i = arr.shift() ) {
  var num = 1 + 1;
}
pending…
forEach
arr.forEach(function (v){
  var num = 1 + 1;
});
pending…
order validation
while( (i = arr.shift()) !== undefined ) {
  var num = 1 + 1;
}
pending…
While ! Undefined
var a;
while((a = arr[i++]) !== undefined) {
  var num = 1 + 1;
}
pending…
Pop
while( i = arr.pop() ) {
  var num = 1 + 1;
}
pending…
Order w/ array copy
var copy = arr.slice(0);
while( i = copy.shift() ) {
  var num = 1 + 1;
}
pending…
While length--
var l = arr.length;
while(l--) {
  var num = 1 + 1;
}
pending…
Emulate .NET foreach
var len = arr.length;
for (var i = 0, x = arr[i]; i < len; ++i) {
  var num = 1 + 1;
}
pending…
Most popular loop on SO
// Source: http://stackoverflow.com/a/7252102/456584
for (var i = 0, len = arr.length; i < len; i++) {
  var num = 1 + 1;
}
pending…
Emulate .NET foreach no assignment
var len = arr.length;
for (var i = 0; i < len; ++i) {
  var num = 1 + 1;
}
pending…
Basic for !==
var len = arr.length;
for (var i = 0; i !== len; ++i) {
  var num = 1 + 1;
}
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. Here’s a list of current revisions for this page:

0 comments

Add a comment