Loops (v201)

Revision 201 of this benchmark created by bob on


Preparation HTML

<script>
   var i,
        arr = [],
        sum = 0
    
    
    for (i = 0; i < 10000; i++) {
        arr[i] = Math.random();
    }
</script>

Setup

Array.prototype.my_forEach = function (f)
        {
            for(var k = -1, m = this.length; ++k<m;)
                if(k in this) f(this[k], k, this)
        }
    
    var my_forEach = function (A, f)
        {
            for(var k = 0, m = A.length; k<m; k++)
                if(k in A) f(A[k], k, A)
        }

Test runner

Ready to run.

Testing in
TestOps/sec
while loop that imitates a for loop
var i = 0;
while (i < arr.length) {
 sum+=arr[i];
 i++;
};
ready
while loop that imitates a for loop, caching the length
var i = 0,
    len = arr.length;
while (i < len) {
 sum+=arr[i];
 i++;
};
ready
Reverse while loop
var i = arr.length;
while (i--) {
 sum+=arr[i];
};
ready
Reverse while loop without implicit ToBoolean
var i = arr.length;
while (i-- > 0) {
 sum+=arr[i];
};
ready
Reverse do … while loop
var i = arr.length;
do {
 sum+=arr[i];
} while (i--);
ready
Reverse for loop
for (var i = arr.length; i--;) {
 sum+=arr[i];
};
ready
Old ’n’ busted for loop
for (var i = 0; i < arr.length; ++i) {
 sum+=arr[i];
};
ready
Old ’n’ busted for loop, caching the length
for (var i = 0, len = arr.length; i < len; ++i) {
 sum+=arr[i];
};
ready
Cool guy loop
for (var i = -1; ++i < arr.length;) {
 sum+=arr[i];
};
ready
Cool guy loop, caching the length
for (var i = -1, len = arr.length; ++i < len;) {
 sum+=arr[i];
};
ready
Native Array#forEach implementation
arr.forEach(function(x) {
 sum+=x;
});
ready
Native Array#forEach implementation with named function
function foo(x) {
 sum+=x;
};
arr.forEach(foo);
ready
perso implement
arr.my_forEach(function (x) {sum+=x;});
ready
perso2
my_forEach(arr, function(x) {sum+=x;});
ready

Revisions

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