Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Created July 20, 2011 18:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidfowl/1095586 to your computer and use it in GitHub Desktop.
Save davidfowl/1095586 to your computer and use it in GitHub Desktop.
Generic memoize function
public static class FuncExtensions {
public static Func<TKey, TResult> Memoize<TKey, TResult>(this Func<TKey, TResult> f) {
return f.Memoize(EqualityComparer<TKey>.Default);
}
public static Func<TKey, TResult> Memoize<TKey, TResult>(this Func<TKey, TResult> f, IEqualityComparer<TKey> equalityComparer) {
var cache = new ConcurrentDictionary<TKey, Lazy<TResult>>(equalityComparer);
return key => {
var lazy = cache.GetOrAdd(key, new Lazy<TResult>(() => f(key)));
return lazy.Value;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment