Reputation: 5127
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]);
}
Upvotes: 2
Views: 203
Reputation: 708156
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 using for (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 for i
:
0
1
2
3
$family
$constructor
each
clone
clean
invoke
associate
link
contains
append
getLast
getRandom
include
combine
erase
empty
flatten
pick
hexToRgb
rgbToHex
which appears to be a bunch of methods that mootools has added to the array object.
Upvotes: 3
Reputation: 7264
I don't know across browsers, but in my test with Firefox there is. for (i=0; etc...)
is much faster. Here is a jsfiddle example that shows the difference. http://jsfiddle.net/pseudosavant/VyRH3/
Add to that the problems that you can encounter with (for i in etc)
when the Array
object has been prototype (perhaps in a library), you should always use for (i=0; etc...)
for looping over arrays.
(for i in etc)
should only ever be used on objects.
Upvotes: 0