What is memoization?

Memoization is a specific form of caching used in dynamic programming. Caching is a way to speed our programs and hold some data in an accessible box for later use. It stores the previous result and returns the others instantaneously when we call without delay.

In addition, memoization is an optimization technique in caching that results when the same set of arguments result in the same output and performant web applications.

Fibonacci sequence

Let’s write a function to compute the Fibonacci sequence without memorization.

The Fibonacci sequence represents a list of numbers where each value is the sum of the two previous values.

Console

From the code above, we didn’t cache the execution of our function. The process will be a lot quicker in less time with caching.

Console

From the code snippet above, we created a cache object that the fib() uses to store its output value. Each time the function is called, it first checks whether the input num has been stored previously in the cache object. If it has, it immediately returns the cached value as the program

Exercise

Let’s find the factorial of a given number using the cache execution of a factorial() function.

Console