Are there any performance difference between
var a = [10,20,30,40];// Assume we have thousands of values here
// Approach 1
var i, len = a.length;
for(i=0;i<len;i++){
alert(i);
alert(a[i]);
}
// Approach 2
for( i in a ){
alert(i);
alert(a[i]);
}
Use
for (var i = 0, len = a.length; i < len; i++)because it’s way faster and it’s the correct way or iterating the items in an array.First: It’s not correct to iterate arrays with
for (i in a)because that iteration will include enumerable properties in addition to array elements. If any methods or properties have been added to the array, they will be part of the iteration when usingfor (i in a)which is never what you want when trying to traverse the elements of the array.Second: The correct option is a lot faster (9-20x faster). See this jsPerf test which shows the
for (var i = 0; i < len; i++)option to be about 9x faster in Chrome and even more of a speed difference in Firefox: http://jsperf.com/for-loop-comparison2.As an example of the problems that can occur when using
for (var i in a), when I use that when the mootools library is included in the project, I get all these values fori:which appears to be a bunch of methods that mootools has added to the array object.