
JavaScript Loop Performance
Planted:
Status: decay
Hits: 250
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
and.map
are declarative. - ▪ Imperative: a paradigm where you describe HOW the program should do something. For example,
for..of
andfor
loops.
Below is the performance of different looping approaches for 3 common tasks; for each, map, and reduce.
For Each
Map
Reduce

Results
- ▪ Imperative loops are more performant than declarative. Invoking callback functions is not free and adds up.
- ▪
for..of
andfor
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:- 1. Check
i < array.length
- 2.
i++
- 1. Check
- ▪ for every iteration in a
for..of
loop:- 1. Call an interator method
- 2. Declare and 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?
Feedback
Have any feedback about this note or just want to comment on the state of the economy?