Chapter 10. Memoization
Using pure functions has more advantages than just producing predictable results. Granted, that’s a good thing to have, but there’s another way to use that behavior to our advantage.
Memoization is somewhat like caching, specifically like the GetOrAdd() function from the MemoryCache() class. Memoization takes a key value of some kind, and if that key is already present in the cache, it returns the object. If the key isn’t present, you need to pass in a function that will generate the required value. Unlike with standard caching, you don’t need to be concerned with cache invalidation or updating values already stored. Typically, memoization holds onto values for the duration of a larger calculation and then discards everything it has stored.
Memoization works to the exact same principle as standard caching, except its scope might not extend beyond a single unit of work, which might be simply a single calculation. It isn’t a replacement for standard caching.
Memoization is useful in a multistep calculation that might be recursive, or involve the same calculations being performed multiple times for some reason. Maybe the best way to explain this is with an example.
Bacon Numbers
Have you ever wanted an entertaining way to waste an afternoon or two? Have a look into Bacon numbers. They’re based on the idea that Kevin Bacon is the center of the acting universe, connecting all actors together. Like all roads lead to Rome, all actors somehow connect at some level ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access