Left Arrow

Notes

Loops

Tachometer

JavaScript Loop Performance

Planted

Status: decay

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 and for loops.

Below is the performance of different looping approaches for 3 common tasks; for each, map, and reduce.

For Each

A bar graph comparing the performance of 3 looping approaches. Showing for..of and for loops are significantly quicker than .forEach.

Map

A bar graph comparing the performance of 3 looping approaches. Showing for loop is significantly quicker than for..of and .forEach.

Reduce

A bar graph comparing the performance of 3 looping approaches. Showing for..of and for loops are significantly quicker than .forEach.
A baby test dummy being fired upon by machine guns while 2 people watch.

Results

  • Imperative loops are more performant than declarative. Invoking callback functions is not free and adds up.
  • for..of and 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++
  • for every iteration in a for..of loop:
    • Call an interator method
    • Declare and initialize a new variable const item
placeholder.

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?

Where to Next?

JavaScript
Performance
Arrow pointing downYOU ARE HERE
Loops
A sci-fi robot taxi driver with no lower body