JavaScript's For-Of Loops Are Fast
4 months ago
- #JavaScript
- #Performance
- #V8
- JavaScript's for-of loops are now nearly as fast as traditional indexed loops due to V8 optimizations.
- Benchmark tests were conducted on arrays of integers, floats, strings, objects, and mixed values with sizes 5000, 50000, and 500000.
- Six loop types were tested: classic for with i++, classic for with cached length, reversed classic for, for-of, for-in, and forEach.
- Results showed that classic i++ with cached length and for-of loops performed best, with for-of sometimes lagging in large arrays.
- Warmup runs improved for-of loop performance, bringing it closer to classic loops.
- For performance-sensitive code, classic i++ with cached length is the most consistent, but for-of is recommended for better ergonomics in non-critical cases.