Fastest array loops in Javascript (v506)

Revision 506 of this benchmark created on


Setup

"use strict";
  var arr2 = [];
  var arr = [];
  for (var i = 0; i < 100; i++) {
  arr2[i] = {i: ""+i};
  arr[i] = {i: ""+i};
  }
  
  function someFn(a) {};

Test runner

Ready to run.

Testing in
TestOps/sec
For loop, basic
"use strict";
for (var i = 0; i < arr.length; i++) {
  someFn(arr[i]);
  someFn(arr2[i]);
}
ready
For loop, basic, preinc
"use strict";
for (var i = 0; i < arr.length; ++i) {
  someFn(arr[i]);
  someFn(arr2[i]);
}
ready
While loop, basic
"use strict";
var i = 0;
while (i < arr.length) {
  someFn(arr[i++]);
  someFn(arr2[i]);
}
ready
For loop, cached
"use strict";
for (var i = 0, len = arr.length; i < len; i++) {
  someFn(arr[i]);
  someFn(arr2[i]);
}
ready
For loop, dec
"use strict";
for (var i = arr.length - 1; i >= 0; i--) {
  someFn(arr[i]);
  someFn(arr2[i]);
}
ready
Do-while loop, --i
"use strict";
var i = arr.length;
if (i)
  do {
    someFn(arr[--i]);
    someFn(arr2[i]);
  } while (i);
ready
shift()
"use strict";
var temp = [];
var temp2 = [];
var value;
var paska;

while (value = arr.shift()) {
  paska = arr2.shift();
  someFn(paska);
  someFn(value);
  temp.push(value);
}

arr = temp;
arr2 = temp2;
ready
pop()
"use strict";
var temp = [];
var temp2 = [];
var value;
while (value = arr.pop()) {
var paska = arr2.pop();
  someFn(paska);
  someFn(value);
  temp.push(value);
}

arr = temp;
arr2 = temp2;
ready
forEach
"use strict";
arr.forEach(function(v) {
  someFn(v)
});

arr2.forEach(function(v) {
  someFn(v)
});
ready
forEach direct
"use strict";
arr.forEach(someFn);
arr2.forEach(someFn);
ready

Revisions

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