JavaScript Memoization Patterns

Taha El Bouffi
Feb 27 · 3 min read

What is Memoization?

Memoization is an optimisation technique base on remembering results returned by a function called with same arguments.

If we have a pure function that consume intensive computation, then we can use memoization.

The memoization will help us store the output value that has already been achieved and then the next time the function is called with the same input value it can simply return the stored value without going through all the computations.

Memoize Fibonacci

Without memoisation computations are excessive, and time consumed for the following function is 4727 ms :

Thanks to memoization we gain a lot in performance, and the time consumed decreased to 1ms :

Memoization Patterns

There are a couple of patterns for implementing memoization:

  • Function as an object
  • Higher Order Function
  • Closures

Function as an Object

Function as an object (which it is actually) where we store the cached value (instead of using global variable) is our first way of memoization, as shown in the example bellow:

We see that we the result is cached in the function as long as the process is alive.

Same goes for Fibonacci function

And same behavior when we have multiple arguments

Higher Order Function Memoization

Higher Order Function is our second way for memoizing, as we see in this example where we enclose our function to memoize inside a Higher Order Function:

Closure Memoization

The third way of memoization that we can use and also the fastest way is using closure. For example we can memoize a recursive function from the first call by setting it as an inner function that will have a closure.

We can find the code used in the above examples here.

Nerd For Tech

From Confusion to Clarification

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store