Memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously-processed inputs.
This is not the same as caching; caching is a more general term. This specifically means caching the results of function calls.
I've built a small Memoization library. In this series of articles, we will explore its usage of a bit of code acrobatics, several ways to do each thing, and one really cool feature - the memoizer itself is memoized.
Today, I would like to introduce the interface design.
First, I wanted to keep this simple. There is only one public static overloaded method, named Memoizer.GetMemoizer().
This method is Generic, and overloaded by number of input parameters. Currently, there are up to three supported parameters for a function, but this can easily be increased.
The overloads are:
Let's start with the first overload. The parameter is a function that accepts no arguments, and returns some TResult.
For example, say I need pi to a million decimal places. I'll keep it as a string to keep things simple.This is a simple method that returns the value for pi to a million places. This is, in fact, a terrible function, but it will serve its purpose. Lucky it's not in production code!
When we run code that uses this function, we have a noticeable delay while the just-over-1MB file is downloaded from www.piday.org. Suppose we call it multiple times? That's why we memoize the result.
Now, the first time we call GetPi, it will download the contents. The second time, it will simply return the same precalculated string. The upside is that calling the function again will be quick. The downside - This 1000002 character string is kept in memory as long as the Func<string> object is.
Next time, I'll quickly go through the other overloads, and introduce my first test cases.