Left Arrow.Back
Left Arrow.Back

Notes / JavaScript / Loop Performance

Loop Performance

A tachometer

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

A bar graph comparing the performance of 3 looping approaches. Showing for..of & 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 & .forEach.

Reduce

A bar graph comparing the performance of 3 looping approaches. Showing for..of & for loops are significantly quicker than .forEach.
Source
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 & 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:
    1. Check i < array.length
    2. i++
  • for every iteration in a for..of loop:
    1. Call an interator method
    2. Declare & initialize a new variable const item
Source
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?