Skip to content

Instantly share code, notes, and snippets.

@joeriks
Last active December 27, 2015 18:19
Show Gist options
  • Save joeriks/7369139 to your computer and use it in GitHub Desktop.
Save joeriks/7369139 to your computer and use it in GitHub Desktop.
Memoize by Joe Albahari https://t.co/TvXLvFqoOR
void Main()
{
Expensive(100).Dump(); // takes 2 secs
Expensive(100).Dump(); // immediate
ExpensiveOther(100).Dump(); // takes 2 secs
ExpensiveOther(100).Dump(); // immediate
}
static int SomeNsExpensive(int x) {Thread.Sleep(2000);return x*10;}
readonly Func<int, int>
Expensive = Memoize<int,int>(SomeNsExpensive);
readonly Func<int, int>
ExpensiveOther = Memoize<int,int>(SomeNsExpensive);
static Func<TIn, TOut> Memoize<TIn,TOut> (Func<TIn, TOut> func) {
var cache = new Dictionary<TIn, TOut>();
return (input => {
TOut result;
if (cache.TryGetValue (input, out result)) return result;
return cache[input] = func(input);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment