Brad Woods Digital Garden

Notes / JavaScript / Performance / Loops

The Warhammer 40k Adeptus Mechanicus symbol

Table of contents

    A tachometer

    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 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:
      1. 1. Check i < array.length
      2. 2. i++
    • for every iteration in a for..of loop:
      1. 1. Call an interator method
      2. 2. 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?

    Feedback

    Have any feedback about this note or just want to comment on the state of the economy?

    Where to next?

    JavaScript
    Performance
    Arrow pointing downYOU ARE HERE
    A Johnny Cab pilot