Fastest way of transversing an array

JavaScript performance comparison

Revision 5 of this test case created

Info

This is meant to test which way is the fastest to transverse an array, specially when performance is important

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var thingy = [1, "test", 44, true, false, "tester", 212313213, "testestetestetest stest ,...!", 2, true, "more", "extra", "stuff", "to", "make", "it", "more", "challenging"];
    var thingy2;
   
    var testArray = [];
    for (i = 0; i < 100000; i++) {
      testArray.push(i);
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
For In
for (var i in thingy) {
  thingy2 = i;
}
pending…
For Loop
for (var i = 0; i < thingy.length; i++) {
  thingy2 = thingy[i];
}
pending…
For Loop (Length Cached)
var length = thingy.length;
for (var i = 0; i < length; i++) {
  thingy2 = thingy[i];
}
pending…
For Loop (Length Cached in for)
for (var i = 0, length = thingy.length; i < length; i++) {
  thingy2 = thingy[i];
}
pending…
Backwards for loop
for (var i = thingy.length - 1; i >= 0; i--) {
  thingy2 = thingy[i];
}
pending…
Backwards for loop (less commands)
for (var i = thingy.length; i--;) {
  thingy2 = thingy[i];
}
pending…
large array for.
for (i = 0; i < testArray.length; i++) {
  thingy2  = testArray[i];
}
pending…
large array for with cached length.
var testArrayLength = testArray.length;
for (i = 0; i < testArrayLength; i++) {
  thingy2  = testArray[i];
}
pending…
large array for in test.
for (i in testArray) {
  thingy2  = testArray[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. Here’s a list of current revisions for this page:

0 comments

Add a comment