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?
This is a micro optimisation at best. Unless you have hundreds of thousands of elements in your
deleteIdsarray, you should not be looking at optimising this.It turns out that the
for(;;;)version is quicker thanfor 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).
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 infor (;;;);(live example):You can use
hasOwnPropertyto eliminate the attributes inherited from the prototype chain, but that won’t stop you receiving methods directly on the object (live example):It is because of these reasons that using
for infor iterating over an array is discouraged, and thefor(;;;)version should always be used instead.for inshould be used for iterating over an object.