What is memoization? Well, I can hardly do a better job than Douglas Crockford, but suffice to say, if you would rather store the results of a previously executed function than execute it again, given the same inputs, then you should memoize the function. You trade memory for speed. You trade a “pure” function for state.
If you get this question in an interview, you’ll need to describe a function that takes a function and returns a function with a cache (either in a closure or attached to the function object), the ability to create and compare cache keys, and the ability to save and return the value of the provided function. If this doesn’t make sense, try looking at this old article by Addy Osmani, or checking out the “matured” implementation here.
Under the right circumstances, this makes perfect sense. But most implementations restrict you to primitive
arguments (those that can be compared using
===). And in the simplest implementation, you can only account for a
single argument. Given our new paradigms of functional, reactive code, these implementations fall short of
their famed utility.
In the past, like Addy’s
version, I used
JSON.stringify to create my cache key, but you can’t pass a function that way and you can’t pass
other complex objects that don’t have a
.toJSON method. Even if you could serialize these objects or functions, you might miss
things like closures.
Another way to structure the cache uses a WeakMap but this requires you to keep the references to the arguments in a manner that could bloat memory even faster. Nothing passed in ever gets garbage collected! Not to mention, that’s a lot of code to get it right. I perfer a simpler approach.
While playing with the Immutable.js api, I realized that the
generated by immutable could be used as a perfect cache key for non-primitive arguments. So, I made and
imemoize, yeah it’s a dumb name but it wasn’t
taken. If you’re already using
immutable or if you have a really heavy process you want to memoize, take it for
a spin. I’m eager to find out if it can help speed up redux apps or other imutable-friendly patterns.