Fastest array loops in Javascript

JavaScript performance comparison

Revision 121 of this test case created by Heavensrevenge

Preparation code

<script src="https://code.jquery.com/jquery-git2.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  // Populate the base array
  var arr = [];
  for (var i = 0; i < 20; i++) {
    arr[i] = (Math.random() * 1000 |0);
  }
  
  function someFn(ix) {
    return ix << 1;
  }
  var len = arr.length, i = 0, arr2 = arr.slice();

};

Benchmark.prototype.teardown = function() {
  i = 0; // reset counters if modified
  arr = arr2.slice(); // repopulate by copying back

};
</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, cached+init
for (var i = 0; i < len; i++) {
  someFn(arr[i]);
}
pending…
For loop, i--
for (var i = len; i > 0; i--) {
  someFn(arr[i]);
}
pending…
For loop, basic
for (var i = 0; i < arr.length; i++) {
  someFn(arr[i]);
}
pending…
While loop, basic
while (i < len) {
  someFn(arr[i]);
  i++;
}
pending…
Do-while loop, i--
var i = len - 1;
do {
  someFn(arr[i]);
} while (i--);
pending…
Do-while loop, --i
var i = len;
if (i > 0) {
  do {
    someFn(arr[i]);
  }
  while (--i);
}
pending…
For..in loop
for (var i in arr) {
  someFn(arr[i]);
}
pending…
shift 1
while (i = arr.shift()) {
  someFn(arr[i]);
}
pending…
forEach
arr.forEach(function(v) {
  someFn(arr[v]);
})
pending…
shift 2
while ((i = arr.shift()) !== undefined) {
  someFn(arr[i]);
}
pending…
While ! Undefined
var a;
while ((a = arr[i++]) !== undefined) {
  someFn(arr[a]);
}
pending…
Pop
while ((i = arr.pop()) !== undefined) {
  someFn(arr[i]);
}
pending…
Order w/ array copy
var copy = arr.slice(0);
while (i = copy.shift()) {
  someFn(arr[i]);
}
pending…
While length--
var l = len;
while (l--) {
  someFn(arr[l]);
}
pending…
pop2
i = arr.pop();
while (i !== undefined) {
  someFn(arr[i]);
  i = arr.pop();
}
pending…
non-init for
for (; i < len; ++i) {
  someFn(arr[i]);
}
pending…
Object.keys
Object.keys(arr).forEach(function(i) {
	someFn(arr[i]);
});
pending…
while non cached len
while (i < arr.length) {
  someFn(arr[i]);
  i++;
}
pending…
while obj.keys.length
var i = Object.keys(arr).length;
while (i--) {
  someFn(arr[i]);
}
pending…
jQuery
$.each(arr, function(index, value) {
 someFn(arr[value]);
});
pending…
pop3
while (i = arr.pop()) {
  someFn(arr[i]);
}
pending…
shift 3
i = arr.shift();
while (i !== undefined) {
  someFn(arr[i]);
  i = arr.shift();
}
pending…
noncached inline while
while (i++ < arr.length) {
  someFn(arr[i]);
}
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