Posts

Showing posts from March, 2013

Memoization

I've spent a couple of hours to write a couple of helper classes to help with the memoization of function calls. Since I haven't found anything as elegant on Google, I thought I'd put them here in case anyone else can use them. Caveat : the code is not thread-safe. I didn't have a use case for it and thread safety is tricky so I didn't want to spend the time. Do not use in multi-threaded code! First, the Memoizer class: public class Memoizer { public static Func<T> Memoize<T>(Func<T> f) { // do NOT inline - it will create a new one on each subsequent call and thus not cache anything var map = new KeyMap<T>(); return () => map.GetValue(new KeyStruct(), f); } public static Func<T1, T> Memoize<T1, T>(Func<T1, T> f) { // do NOT inline - it will create a new one on each subsequent call and thus not cache anything var map = new KeyMap<T>(); return arg