Skip to content

Instantly share code, notes, and snippets.

@galkin
Created August 22, 2022 14:01
Show Gist options
  • Save galkin/d9fae218b1a568a4c3f07d5c9a22fa98 to your computer and use it in GitHub Desktop.
Save galkin/d9fae218b1a568a4c3f07d5c9a22fa98 to your computer and use it in GitHub Desktop.
JavaScript Loop Benchmark

JavaScript Loop Benchmark

In this benchmark we will compare for(const el of array) vs for(let i = 0; i < array.length; i++). For that we will use hyperfine.

Benchmarks Environment

  • Node.js v16.16.0
  • MacBook Pro (16-inch, 2021) with Apple M1 Pro and 16 GB Memory

Case 1: Empty loop

Details: loop iteration is empty. Command: hyperfine --warmup 1 'node empty_for_i.js' 'node empty_for_of.js' Result:a

❯ hyperfine --warmup 1 'node empty_for_i.js' 'node empty_for_of.js'
Benchmark 1: node empty_for_i.js
  Time (mean ± σ):     108.9 ms ±   0.8 ms    [User: 104.4 ms, System: 3.5 ms]
  Range (min … max):   108.1 ms … 111.5 ms    27 runs

Benchmark 2: node empty_for_of.js
  Time (mean ± σ):     191.4 ms ±   1.3 ms    [User: 186.2 ms, System: 4.0 ms]
  Range (min … max):   190.0 ms … 194.4 ms    15 runs

Summary
  'node empty_for_i.js' ran
    1.76 ± 0.02 times faster than 'node empty_for_of.js'

Case 2: Not Empty loop

Details: loop iteration has only Math.random() Command: hyperfine --warmup 1 'node for_i.js' 'node for_of.js' Result:

❯ hyperfine --warmup 1 'node for_i.js' 'node for_of.js'
Benchmark 1: node for_i.js
  Time (mean ± σ):      1.756 s ±  0.003 s    [User: 1.695 s, System: 0.021 s]
  Range (min … max):    1.753 s …  1.760 s    10 runs

Benchmark 2: node for_of.js
  Time (mean ± σ):      1.799 s ±  0.018 s    [User: 1.739 s, System: 0.020 s]
  Range (min … max):    1.783 s …  1.837 s    10 runs

Summary
  'node for_i.js' ran
    1.02 ± 0.01 times faster than 'node for_of.js'

Conclusion

When the loop is empty, bypassing the array is really faster (1.75 times). In real projects, the cycle contains commands and the difference is statistically insignificant.

const array = new Array(1000).fill(0);
const max = 2 ** 18;
for (let i = 0; i < max; i++) {
for (let j = 0; j < array.length; j++) {
const el = array[j];
// do nothing
}
}
const array = new Array(1000).fill(0);
const max = 2 ** 18;
for (let i = 0; i < max; i++) {
for (const el of array) {
// do nothing
}
}
const array = new Array(1000).fill(0);
const max = 2 ** 18;
for (let i = 0; i < max; i++) {
for (let j = 0; j < array.length; j++) {
const el = array[j];
Math.random();
}
}
const array = new Array(1000).fill(0);
const max = 2 ** 18;
for (let i = 0; i < max; i++) {
for (const el of array) {
Math.random();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment