I setup a simple benchmark for comparing performance of for (const x of arr) and for (let i = 0; i < arr.length; i++) loops. (benchmark link)
Setup code
const arr = [...new Array(10000)].map(() => Math.random()); for (let i = 0; i < arr.length; i++)
let sum = 0; for (let i = 0; i < arr.length; i++) { sum += arr[i]; } for (const x of arr)
let sum = 0; for (const x of arr) { sum += x; } I have re-run the benchmark several times over, and each time, the for-of loop is almost 70% slower than the for-length loop. (~150k ops/sec vs ~43k ops/sec). This is very surprising to me.
What is the reason for this loop being significantly slower?
I have looked at the related thread and the answers there dive into pros/cons of micro-benchmarking, and the conclusion was that switching the test order results in flipping the result. My case is different because I have large arrays (so no micro-bench issues) and I am using a test framework (jsbench.me) to avoid cold start issues.
for-ofloop uses Iterators (and all the overhead that comes with it) underneath whereas thefor-lengthloop simply iterates over a memory section ?arr.lengthto a variable, because arr.length is an accessor (get/set method)for,for...ofO(1)and even if it would make a difference, this would likely be optimized by the JIT compiler.array.lengthin the array condition is slightly faster (1, 2), once using a separate variable is faster (3).