简体   繁体   中英

Performance's difference between for (var x in array) and for (var x=0, y= array.length; x<y; x++)

When I want to loop through an array and add a string behind every element ,

I can either

for(var x in array){
 array[x] += "string";  
}

or

for(var x, y = array.length; x<y; x++){
 array[x] += "string";  
}

But is there any difference in terms of performance between these 2 for loops ?

It is recommended that you don't use for ... in to iterate over arrays.

ie Why is using "for...in" with array iteration a bad idea?

You should use for ... in to iterate over object properties only.

Usually, for...in is way slower, because it accesses to the array as a common object, while the classic for cycle doesn't need to sort out all the properties of array to perform its task.

Keep in mind that modern browsers have special optimizations for arrays, but you can't exploit them if you're treating them as common objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM