Fastest array loops in Javascript (v467)

Revision 467 of this benchmark created by madreason on


Preparation HTML

<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>

Setup

arr = baseArr /* baseArr.slice() */;

Test runner

Ready to run.

Testing in
TestOps/sec
While length--
var l = arr.length;
while(l--) {
  someFn(arr[l]);
}
ready
While loop, basic
var i = 0;
while (i < len) {
  someFn(arr[i++]);
}
ready
For loop, cached
for (var i = 0, len = arr.length; i < len; i++) {
  someFn(arr[i]);
}
ready
For loop, basic
for (var i = 0; i < arr.length; i++) {
  someFn(arr[i]);
}
ready
For loop, adv
var i = 0, l = arr.length;
for (; i < l; i++) {
  someFn(arr[i]);
}
ready
without length calculation
for (var i = 0; i < len; i++) {
  someFn(arr[i]);
}
ready
Cla
for (var i = 0, l = arr.length; i !== l; i++) {
  someFn(arr[i]);
}
ready
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++]);
}
ready
simple
for (var i = 0, l = len /* arr.length */; i < l; i++) {
  someFn(arr[i]);
}
ready

Revisions

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