JavaScript's for-of loops are actually fast Published on 01/01/2026 Updated on 04/01/2026 When it comes to iterating over arrays, for...of loops are believed to be significantly slower than traditional indexed loops. This has some grounding, since for-of loops are based on the iteration protocol, where the iterator has next() method returning an object like this: { value: /* element value */, done: /* a boolean, indicating the end of iteration */ }. Obviously, returning such object for every element will add an overhead. However, I decided to test this since JS engines are constantly improving and sometimes can do amazing optimizations. Table of contentsThe benchmarkThe core idea of the benchmarkThe setupThe resultsConclusionThe benchmark I decided to do the benchmarks with jsbenchmark.com on Chrome 143, Windows 11 and AMD Ryzen 5000U. All the benchmark tests are run sequentially. The core idea of the benchmark The idea is to create 5 types of arrays: integers, floats, strings, objects and mixed values. The benchmarks will be done with 3 array sizes: 5000, 50000, and 500000. There will be 6 types of loops: Classic for with i++: for (let i = 0; i < arr.length; i++) { DATA.doSomethingWithValue(arr[i]); } Classic for with i++ and cached array length: const length = arr.length; for (let i = 0; i < length; i++) { DATA.doSomethingWithValue(arr[i]); } Classic for with i-- reversed: for (let i = arr.length - 1; i >= 0; i--) { DATA.doSomethingWithValue(arr[i]); } for-of: for (const x of arr) { DATA.doSomethingWithValue(x); } for-in: for (const key in arr) { DATA.doSomethingWithValue(arr[key]); } forEach: arr.forEach(x => DATA.doSomethingWithValue(x)); All the loops call a dummy function DATA.doSomethingWithValue() for each array element to make sure V8 doesn't optimize out something too much. The setup The setup will generate 5 types of arrays: random integers, random floats, random strings, objects and mixed values. It will also create a dummy function doSomethingWithValue ...
First seen: 2026-01-06 07:32
Last seen: 2026-01-06 16:38