by Chris Lyons

Implementing Memoization in a Recursive Fibonacci Sequence Function

TL;DR (Skip to the Final Code)

Below is a recursive fibonacci sequence function with no memoization implementation. It runs very slowly and can be massively improved.

fibonacci.js
Copy

_4
const fibonacci = n => {
_4
if(n < 2) return 1;
_4
return fibonacci(n - 1) + fibonacci(n - 2);
_4
}

You can test the speed with the following code:


_3
console.time();
_3
console.log(fibonacci(999));
_3
console.timeEnd();

Spoiler alert: it’s very slow.

Enter Memoization

The following shows how to implement memoization to greatly increase the function’s speed:

fibonacciMemoized.js
Copy

_11
// First we create a variable to act as our cache.
_11
const cache = [];
_11
_11
const fibonacci = n => {
_11
if(n < 2) return 1;
_11
// Then we check to see if we've already stored a result
_11
// for `n` in our cache. If we have, we return it.
_11
if(cache[n]) return cache[n];
_11
// And if we haven't cached this number yet, we cache it and return it
_11
return cache[n] = fibonacci(n - 1) + fibonacci(n - 2);
_11
}

You can test the speed with the following code:


_11
// First time will be considerably faster than the
_11
// version without memoization.
_11
console.time();
_11
console.log(fibonacci(999));
_11
console.timeEnd();
_11
_11
// Second time finishes WAY faster than even the improved
_11
// times seen with the first call above.
_11
console.time();
_11
console.log(fibonacci(999));
_11
console.timeEnd();

Final Code (Sans Comments)

fibonacciMemoized.js
Copy

_6
const cache = [];
_6
const fibonacci = n => {
_6
if(n < 2) return 1;
_6
if(cache[n]) return cache[n];
_6
return cache[n] = fibonacci(n - 1) + fibonacci(n - 2);
_6
}

There you have it. Now go ace that technical interview!