admin管理员组

文章数量:1390547

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?

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?

Share Improve this question edited Jun 8, 2012 at 12:21 Marcel Korpel 21.8k6 gold badges62 silver badges80 bronze badges asked Jun 8, 2012 at 12:06 user1282226user1282226 7
  • 5 For performance check, try jsperf. – MaxArt Commented Jun 8, 2012 at 12:07
  • 1 Note that in both cases you are adding a string to the index of each element, which will break the second loop (it's broken anyway since you never initialize x). – Felix Kling Commented Jun 8, 2012 at 12:09
  • did you execute and check the output. It's not clear what you want to do. – Romil Kumar Jain Commented Jun 8, 2012 at 12:11
  • 3 Never use for … in to loop through an array, see developer.mozilla/en/JavaScript/Reference/Statements/… and stackoverflow./questions/500504/… – Marcel Korpel Commented Jun 8, 2012 at 12:17
  • 1 jsperf./forinvsfor/5 about 12 times faster in chrome – Esailija Commented Jun 8, 2012 at 12:18
 |  Show 2 more ments

2 Answers 2

Reset to default 5

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

i.e. 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 mon 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 mon objects.

本文标签: