JavaScript Loop Performance
Planted:
Status: seed
Performance is mostly effected by choosing a declarative or imperative programming approach:
- Declarative: a paradigm where you describe WHAT the program does, without specifying how. For example,
Array
methods.forEach
,.reduce
&.map
are declarative. - Imperative: a paradigm where you describe HOW the program should do something. For example,
for..of
&for
loops.
Below is the performance of different looping approaches for 3 common tasks; for each, map, & reduce.
For Each
Map
Reduce
Results
- Imperative loops are more performant than declarative. Invoking callback functions is not free & adds up.
for..of
&for
loops have approx. the same performance for arrays- It's faster to pre-allocate an array with a known length than to rely on
.push
automatic growth (see Map example). - Object destructing does not effect performance.
This makes sense when you break down what each approach is doing:
- for every iteration in a
for
loop:- Check
i < array.length
i++
- Check
- for every iteration in a
for..of
loop:- Call an interator method
- Declare & initialize a new variable
const item

Selecting an Approach
Don't prematurally optimize. When iterating data, selecting an approach shouldn't be based on performance only. Performance is just 1 variable that needs to be considered with others, such as:
- readability (imperative code can be more verbose)
- the amount of data your processing. Is it small enough that performance doesn't matter?