Fastest array loops in Javascript

JavaScript performance comparison

Revision 506 of this test case created by

Preparation code


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

};
</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, basic
"use strict";
for (var i = 0; i < arr.length; i++) {
  someFn(arr[i]);
  someFn(arr2[i]);
}
pending…
For loop, basic, preinc
"use strict";
for (var i = 0; i < arr.length; ++i) {
  someFn(arr[i]);
  someFn(arr2[i]);
}
pending…
While loop, basic
"use strict";
var i = 0;
while (i < arr.length) {
  someFn(arr[i++]);
  someFn(arr2[i]);
}
pending…
For loop, cached
"use strict";
for (var i = 0, len = arr.length; i < len; i++) {
  someFn(arr[i]);
  someFn(arr2[i]);
}
pending…
For loop, dec
"use strict";
for (var i = arr.length - 1; i >= 0; i--) {
  someFn(arr[i]);
  someFn(arr2[i]);
}
pending…
Do-while loop, --i
"use strict";
var i = arr.length;
if (i)
  do {
    someFn(arr[--i]);
    someFn(arr2[i]);
  } while (i);
pending…
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;
pending…
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;
pending…
forEach
"use strict";
arr.forEach(function(v) {
  someFn(v)
});

arr2.forEach(function(v) {
  someFn(v)
});
pending…
forEach direct
"use strict";
arr.forEach(someFn);
arr2.forEach(someFn);
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