kamaci
kamaci

Reputation: 75127

Iterating Performance Comparison

I have an array:

deleteIds= ["User1"];

and try to iterate over it as like:

first one:

for (var index = 0; index < len; index++) {
    alert(deleteIds[index]);
}

second one:

for (var index in deleteIds) {
    alert(deleteIds[index]);
}

What is the performance comparison of them?

Upvotes: 0

Views: 93

Answers (1)

Matt
Matt

Reputation: 75317

This is a micro optimisation at best. Unless you have hundreds of thousands of elements in your deleteIds array, you should not be looking at optimising this.

It turns out that the for(;;;) version is quicker than for in: http://jsperf.com/iterating-over-a-loop/2 (thanks to @Jamiec for the jsperf).

However, what's more important than the performance comparison of these, is that both code snippets are functionally different to each other (live example).

var array = new Array(100);
for (var i = 0; i < array.length; i++) {
    console.log(i); // shows 0 - 99
}

for (var x in array) {
    console.log(x); // shows nothing
}

Furthermore, if you add methods to either the array, or to an object in the arrays' prototype chain, they will show up in the for (var x in y) loop, but not in for (;;;); (live example):

Array.prototype.foo = function() {};
var array = [];
for (var i = 0; i < array.length; i++) {
    console.log(i); // nothing
}

for (var x in array) {
    console.log(x); // `foo`
}

You can use hasOwnProperty to eliminate the attributes inherited from the prototype chain, but that won't stop you receiving methods directly on the object (live example):

Array.prototype.foo = function() {};
var array = [];
array.bar = function () {};

for (var i = 0; i < array.length; i++) {
    console.log(i); // nothing
}

for (var x in array) {
    if (array.hasOwnProperty(x)) {
        console.log(x); // `bar`
    }
}

It is because of these reasons that using for in for iterating over an array is discouraged, and the for(;;;) version should always be used instead. for in should be used for iterating over an object.

Upvotes: 5

Related Questions