Which loop is faster?
In modern JavaScript, the difference in speed between for, while, and for..of is extremely small for most tasks. If you only have 1000 elements in an array, you won't notice the difference.
1. Classical for
The fastest, as the V8 engine (in Chrome and Node.js) has been honing its optimization for decades.
2. for..of
The gold standard for readability. It's slightly slower than a classic for, but in 99% of cases, this isn't critical.
3. for..in — DANGER
This loop was created for iterating over OBJECT properties. When working with an array, it:
- Is 10-50 times slower than the others.
- Iterates over properties out of order.
- Might pick up extra properties from prototypes.
Caution
Never use for..in for arrays.
Tip
The main enemy of loop performance is not the choice of loop type, but the creation of unnecessary objects or functions inside the loop body. This forces the Garbage Collector to work overtime.