Loop iteration (length comparison variations)

JavaScript performance comparison

Revision 17 of this test case created by Mike

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  window.list = [];
  var x = 100;
  for (var y = 0; y < x; y++) {
    window.list[y] = true;
  }

};

Benchmark.prototype.teardown = function() {
  delete window.list;

};
</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
Using list.length
for (var i = 0; i < window.list.length; i++) {
  var fruit = window.list[i];
}
pending…
Using static len - outside for declr.
var len = window.list.length;
for (var i = 0; i < len; i++) {
  var fruit = window.list[i];
}
pending…
Using static len - inside for declr.
for (var i = 0, len = window.list.length; i < len; i++) {
  var fruit = window.list[i];
}
pending…
Reverse Loop (for)
for (var i = window.list.length; i--;) {
  var fruit = window.list[i];
}
pending…
Reverse Loop (while)
var i = window.list.length;
while (i--) {
  var fruit = window.list[i];
}
pending…
Reverse Loop (for) w/ outside declaration & --
var i = window.list.length;
for (; i--;) {
  var fruit = window.list[i];
}
pending…
Reverse Loop (for) w/ outside declaration & >= 0
var i = window.list.length,
    fruit;
for (; i >= 0; i--) {
  fruit = window.list[i];
}
pending…
Destructive array - shift
var list = window.list.slice(0),
    fruit = list.shift();
while (fruit) {
  fruit = list.shift();
}
pending…
Destructive array - pop
var list = window.list.slice(0),
    fruit = list.pop();
while (fruit) {
  fruit = list.pop();
}
pending…
Destructive array - pop w/ reverse
var list = window.list.slice(0).reverse(),
    fruit = list.pop();
while (fruit) {
  fruit = list.pop();
}
pending…
iterator object
var ArrayIterator = function(array){
 this.array = array;   
};
ArrayIterator.prototype = {
    head : -1,
    array : null,
    atEnd : function(){
     return this.head == this.array.length - 1;   
    },
    next : function(){
     return this.array[++this.head];   
    }
};

var iterator = new ArrayIterator(window.list), fruit;
while(!iterator.atEnd()){
  fruit = iterator.next();
}
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