2

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?

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
  • 5
    For performance check, try http://jsperf.com/ – MaxArt Jun 08 '12 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 Jun 08 '12 at 12:09
  • did you execute and check the output. It's not clear what you want to do. – Romil Kumar Jain Jun 08 '12 at 12:11
  • Sorry I was being a bit careless just now. –  Jun 08 '12 at 12:14
  • 3
    Never use `for … in` to loop through an array, see https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in and http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays – Marcel Korpel Jun 08 '12 at 12:17
  • 1
    http://jsperf.com/forinvsfor/5 about 12 times faster in chrome – Esailija Jun 08 '12 at 12:18
  • possible duplicate of [performance difference between for loop and for.. in loop when iterating an array in javascript?](http://stackoverflow.com/q/9640949/) – outis Jul 17 '12 at 09:28

2 Answers2

4

It is recommended 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.

Community
  • 1
  • 1
Dennis
  • 14,210
  • 2
  • 34
  • 54
2

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.

MaxArt
  • 22,200
  • 10
  • 82
  • 81