for-loop vs for-in-loop vs foreach-loop

Benchmark created by Enzo on


Setup

for (var arr=[],obj={}, i=0; i<9999; ++i) {
        arr.push(i);
        obj[i]=i;
    }
    delete arr[1];
    delete obj[1];
    var i, len=arr.length;

Test runner

Ready to run.

Testing in
TestOps/sec
for
for (i=0; i<len;i++)
        if (arr[i] !== undefined)
                arr[i];
ready
for typeof
for (i=0; i<len;i++)
        if (typeof arr[i] != 'undefined')
                arr[i];
ready
for hasownproperty
for (i=0; i<len;i++)
        if (arr.hasOwnProperty(i))
                arr[i];
ready
for-in
for (i in arr)
        arr[i];
ready
foreach
arr.forEach(function(item, i){
        item;
});
ready
for obj
for (i in obj)
        obj[i];
ready

Revisions

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