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.