Last active
December 27, 2015 18:19
-
-
Save joeriks/7369139 to your computer and use it in GitHub Desktop.
Memoize by Joe Albahari https://t.co/TvXLvFqoOR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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