Introduction to Memoization in Javascript

Share:
Source Code

We will learn about how you can use Memoization to speed up your application and reduce redundant expensive function calls.

What is Memoization?

In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again

You can use memoization in alot of situations in the real world, as long as three conditions are satisfied:

  1. The function is very computing intensive
  2. You will call this function multiple times with the same input value
  3. The computed result from that function call should be immutable.

Let’s look at a memorized function:

//Javascript Memoization
	var raiseTo100Power = function(base) {
		    raiseTo100Power._cache = raiseTo100Power._cache || {};
		    if (!raiseTo100Power._cache[base]) {
        			console.info('Not found in cache, performing expensive operation and storing in cache');
        			var result;
        			result = Math.pow(base, 100);
        			raiseTo100Power._cache[base] = result;
    		}
    		return raiseTo100Power._cache[base];
	}

For the sake of simplicity, raiseTo100Power is our “resource intensive” function we want to cache the results with.  Of course in the real world, the function could be something a lot more complicated.

The function takes a parameter call base, so let’s go over this function line by line:

Here we store a private variable call _cache and set it to itself, and if it’s not defined, we set it to an empty object:

raiseTo100Power._cache = raiseTo100Power._cache || {};

Next comes the heart of the program:

if (!raiseTo100Power._cache[base]) {
        			console.info('Not found in cache, performing expensive operation and storing in cache');
        			var result;
        			result = Math.pow(base, 100);
        			raiseTo100Power._cache[base] = result;
		}

This will check our cache to see if this particular base value has already been stored in our cache, if it’s not, we let the user know the value has not been found in cache, and thus initiate a variable call result to store the result of our heavy computation to.  Then we set raiseTo100Power.cache[base] to that result.

and of course, outside of this if statement we always want to return:

		return raiseTo100Power._cache[base];

This will return a value because if the value is stored in cache, it will return it and if not it will do the calculations and store it in this cache variable.

Go ahead and test this out by invoking the function with the same parameter a two times, you will notice the result will happen much faster on the second time.

Comments Or Questions? Discuss In Our Discord

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

More from PentaCode