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.
You can test the speed with the following code:
_3console.time();_3console.log(fibonacci(999));_3console.timeEnd();
console.time();console.log(fibonacci(999));console.timeEnd();
Spoiler alert: it’s very slow.
Enter Memoization
The following shows how to implement memoization to greatly increase the function’s speed:
You can test the speed with the following code:
_11// First time will be considerably faster than the_11// version without memoization._11console.time();_11console.log(fibonacci(999));_11console.timeEnd();_11_11// Second time finishes WAY faster than even the improved_11// times seen with the first call above._11console.time();_11console.log(fibonacci(999));_11console.timeEnd();
// First time will be considerably faster than the// version without memoization.console.time();console.log(fibonacci(999));console.timeEnd();// Second time finishes WAY faster than even the improved// times seen with the first call above.console.time();console.log(fibonacci(999));console.timeEnd();
Final Code (Sans Comments)
There you have it. Now go ace that technical interview!