Loops (v41)

Revision 41 of this benchmark created on


Setup

var array = [];
    var n = 100000;
    
    for(var i=1; i<=n; i++) {
        array.push(n);
    }

Teardown


    console.log(total);
  

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
var total = 0;
array.forEach(function(val) {
  total += val;
});
ready
for optimized
var total = 0;

for(var i=0,n=array.length; i<n; i++) {
    total += array[i];
}
ready
for standard
var total = 0;

for(var i=0; i<array.length; i++) {
    total += array[i];
}
ready
for reversed
var total = 0;

for(var i=array.length-1; i>=0; i--) {
    total += array[i];
}
ready
while
var total = 0;
var length = array.length;

while (length--) {
    total += array[length];
}
ready
doubled loop
var total = 0;

for(var i=0;i <= array.length-2; i+=2) {
    total += array[i] + array[i+1];
}

if (array.length % 2) {
    total += array[array.length-1];
}
ready

Revisions

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