JavaScript Arrays – Why ‘For-Of’ Loop is Faster for Small Arrays

arraysjavascriptperformance

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?

Best Answer

When benchmarking smaller values, the overhead operations can have a bigger impact on the test.

For example, if variable initialization and memory allocation takes 0.1 ms, this is negligible with n > 1000, however significant with n = 10.

In this case, the for/of operator allows the V8 engine to optimize the loop operation (reducing the overheads like above). For example it may pre-load the array items onto the stack or similar.

The for/let operation will process each item independent of the whole array, and is more explicit in variable usage (reducing the amount of optimization the engine can do).

Related Question