Improve Performances using Memoization

Michele Riva
openmind
Published in
3 min readJun 23, 2019

--

Memoization is an optimization technique used to improve performances of a given algorithm/program by storing the result of expensive function calls and returning a cached result whenever the same input occurs again.

We’ll be using the Fibonacci Sequence as an example to see Memoization in depth.
We actually have multiple ways to compute the Fibonacci Sequence in JavaScript; two of the most popular ways are the Iterative and the Recursive ones:

Iterative

Recursive

The recursive one is actually more coincise and clearer but comes with a cost: performances.
As we’ve seen in the previous article, Adopting Memory Safe Recursion, we can use trampolines to convert recursive calls in a while loop, which can help us improving both performances and memory safety.
But if we just have a performances problem, we can act differently adopting Memoization:

--

--