for loop research (v15)

Revision 15 of this benchmark created on


Description

Varius for-loop variants: * with length caching * with various counter increment (++i, i++) * while alternative

Setup

var arr = [];
    
    for (var i=0; i<1000; i++) {
      arr.push('arr-value-' + i);
    }
    
    function worker(a) {
      console.log(arr[a]);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
classic for-loop
for (var i=0; i < arr.length; i++) {
  worker(i);
}
ready
++i
for (var i=0; i < arr.length; ++i) {
  worker(i);
}
ready
caching length in loop
for (var i=0, len=arr.length; i<len; i++) {
  worker(i);
}
ready
caching length outside loop
var len=arr.length;

for (var i=0; i<len; i++) {
  worker(i);
}
ready
double caching length
var len=arr.length;

for (var i=0, ilen=len; i<ilen; i++) {
  worker(i);
}
ready
while alternative i--
var i = arr.length;
while (i--) {
  worker(i);
};
ready
while alternative --i
var i = arr.length;
while (--i) {
  worker(i);
};
ready
another for
for (var i = -1, length = arr.length; ++i < length; ) {
  worker(i);
}
ready

Revisions

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