Fastest array loops in Javascript

JavaScript performance comparison

Revision 467 of this test case created by madreason

Preparation code

<script>
  // Populate the base array
  var baseCount = 10000;
  var baseArr = new /*Array*/Uint16Array(baseCount);
  for (var i = 0; i < baseCount; i++) {
    baseArr[i] = i;
  }
  var len = baseArr.length;
  function someFn(ix) {
    return ix * 5 + 1 / 3 * 8;
  }
</script>
      
<script>
Benchmark.prototype.setup = function() {
  arr = baseArr /* baseArr.slice() */;

};
</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
While length--
var l = arr.length;
while(l--) {
  someFn(arr[l]);
}
pending…
While loop, basic
var i = 0;
while (i < len) {
  someFn(arr[i++]);
}
pending…
For loop, cached
for (var i = 0, len = arr.length; i < len; i++) {
  someFn(arr[i]);
}
pending…
For loop, basic
for (var i = 0; i < arr.length; i++) {
  someFn(arr[i]);
}
pending…
For loop, adv
var i = 0, l = arr.length;
for (; i < l; i++) {
  someFn(arr[i]);
}
pending…
without length calculation
for (var i = 0; i < len; i++) {
  someFn(arr[i]);
}
pending…
Cla
for (var i = 0, l = arr.length; i !== l; i++) {
  someFn(arr[i]);
}
pending…
splited loop
var testVal = 0;
var n = len /* arr.length */ % 8;
for (var i = 0, count = n; i < n; i++) {
  someFn(arr[testVal++]);
}

n = (len /* arr.length */ * 0.125) ^ 0; //multiplication is faster than division in some cases
for (var i = 0, count = n; i < n; i++) {
  someFn(arr[testVal++]);
  someFn(arr[testVal++]);
  someFn(arr[testVal++]);
  someFn(arr[testVal++]);
  someFn(arr[testVal++]);
  someFn(arr[testVal++]);
  someFn(arr[testVal++]);
  someFn(arr[testVal++]);
}
pending…
simple
for (var i = 0, l = len /* arr.length */; i < l; i++) {
  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