-1

I was curious if anybody knows if one is faster than the other in either specific use cases or in general, and why.

Specifically, I'm referring to

for (let myVariable in myArray) { *do something* }

and

myArray.forEach(myVariable => { *do something* })
chazsolo
  • 7,873
  • 1
  • 20
  • 44
yoursweater
  • 1,883
  • 3
  • 19
  • 41
  • 6
    `for..in` should be used for iterating the keys of an object, while `forEach` would be more equivalent to a regular `for` loop. `for...of` is basically the same as `forEach` - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in - note specifically where it says `for...in should not be used to iterate over an Array where the index order is important.` – tymeJV Jan 30 '19 at 14:01
  • 2
    Also, relevant - [don't use `for...in` with arrays](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea) – VLAZ Jan 30 '19 at 14:01
  • 2
    Possible duplicate of [Javascript efficiency: 'for' vs 'forEach'](https://stackoverflow.com/questions/43031988/javascript-efficiency-for-vs-foreach) – Harshit Jan 30 '19 at 14:03
  • 1) It's not a duplicate question. for...in is not the same as a for loop. 2) Vlaz, yes, it's optimization. Thank you for your invaluable insights. 3) tymeJV thanks for actually helping to answer the question instead of making snarky comments or incorrectly labeling this as a duplicate – yoursweater Jan 30 '19 at 19:32

2 Answers2

1

I found an article to back up my opinion that for loops must be faster since they don't have a callback to deal with Wich also is my answer.

https://hackernoon.com/javascript-performance-test-for-vs-for-each-vs-map-reduce-filter-find-32c1113f19d7

0
myArray.forEach(myVariable => { *do something* })

If you use this it'll optimize your code and speed. As forEach loop won't create external indexing like for loop. More of above it will allow you to access it's different elements easily. For further use cases, you may visit www.javascriptinfo.com

  • 1
    Chiragkumar, to the best of my knowledge a regular for loop is faster than .forEach(), and for...of is even faster than that. I'm not sure .forEach() optimizes for speed – yoursweater Jan 30 '19 at 19:34
  • Hi, yoursweater, Kindly analyse below information. foreach vs. for: Performance When accessing collections, a foreach is significantly faster than the basic for loop’s array access. When accessing arrays, however–at least with primitive and wrapper-arrays–access via indexes is dramatically faster. Timing the difference between iterator and index access for primitive int-arrays Indexes are 23-40 percent faster than iterators when accessing int or Integer arrays. – Chiragkumar Maniar Jan 31 '19 at 17:33