Recently I made a post on how to create memoized functions using a class. Well today I came across a post that shows how to do the same thing using an extension method, so I thought I would share the code.
public static class Extensions
{
public static Func<A, R> Memoize<A, R>(this Func<A, R> f)
{
var map = new Dictionary<A, R>();
return a =>
{
R value;
if (map.TryGetValue(a, out value))
return value;
value = f(a);
map.Add(a, value);
return value;
};
}
}
Then you use it like so.
class TestIt
{
public int DoIt(string parameter)
{
// Do lots of processing...
return 0;
}
public void Test()
{
// Wrap the function and then use the Memoize extension method.
var func = new Func<string, int>(DoIt).Memoize();
// The function can then be executed as it if were a normal function.
// This is different than before because you had to call execute.
var result = func("process me");
}
}
The only limitation is that you have to create different extension methods based on the number of parameters.