Suppose (entirely hypothetically ;) ) that I have nuget package, which essentially exposes a set of static extension methods:
public static class MyNugetLibrary
{
public static int DoSomethingExpensiveAndUseful(this string input)
{
return input.Length;
}
public static int DoSomethingElseExpensiveAndUseful(this string input)
{
return (int)input.ToCharArray().First();
}
}
And, for sane reasons, I conclude that what this package really needs is caching. The output is constant given the input, and the input is something primitive.
In my case there's no conceivable way for the output to change, so I never have to worry about cache invalidation etc.
If there were just 1 or 2 methods I could just add a private static Dictionary to the extension class, and in the method ask the dictionary for the answer.
But I'd quite like to not duplicate so much code, and there's a really nice memoize function:
public static Func<T, TResult> Memoize<T, TResult>(this Func<T, TResult> f)
{
var cache = new ConcurrentDictionary<T, TResult>();
return a => cache.GetOrAdd(a, f);
}
(Stolen from here: https://www.aleksandar.io/post/memoization/)
But I can't quite figure out how to use that method to make these functions memoized, without changing the external interface of my package.
How can I do this?
Massive bonus points available if we can further do this in such a way that the caching can be disabled by the end user (MyNugetLibrary.DisableCaching()
) in case they are worried about, e.g. the memory footprint.