Tuesday, 25 December 2018

Why is for-of loop faster than standard for loop for small arrays and slower for larger arrays?

In JavaScript, I noticed that the ES6 for ... of loop has a much different performance than the traditional for (start; stop; step) loop.

Benchmark

const n = 10000;
const arr = Array(n).fill().map((e, i) => i); // [0, n)

console.log('n =', n);

let sum1 = 0;
console.time('for let i');
for (let i = 0; i < arr.length; i++) {
  sum1 += arr[i];
}
console.timeEnd('for let i');

let sum2 = 0;
console.time('for of');
for (let v of arr) {
  sum2 += v;
}
console.timeEnd('for of');

Results

n = 10
for let i: 0.350ms
for of: 0.015ms
-----
n = 100
for let i: 0.354ms
for of: 0.023ms
-----
n = 1000
for let i: 0.429ms
for of: 0.111ms
-----
n = 10000
for let i: 1.048ms
for of: 2.138ms
-----
n = 100000
for let i: 9.452ms
for of: 13.644ms

(Tested using Node.js v10.11.0)

As you can see, as n increases, the speed of the for-of loop decreases at a faster rate than the standard for loop. Why is the for-of loop faster for smaller arrays and slower for larger ones?



from Why is for-of loop faster than standard for loop for small arrays and slower for larger arrays?

No comments:

Post a Comment