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.
- Node.js v16.16.0
- MacBook Pro (16-inch, 2021) with Apple M1 Pro and 16 GB Memory
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'
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'
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.