Just Lazy Enough.

04 Nov 2012

There’s cases where memoizing a bit of data in memory can make dramatic improvements in performance (like a lookup table that changes infrequently, but is accessed frequently.) We may even find that as long as it’s “eventually consistent”, that’s good enough. The .net 4.0 framework introduced a brilliant little class called Lazy. With this class, you could pass a function that would get called once when a value was requested, and then would be stored for future requests. This was helpful when you didn’t know exactly when an expensive resource would be needed, or it didn’t make sense to load it at the moment when they system was getting initialized, for example. One drawback of the Lazy is that it will resolve the value one time, and then keep it for the lifetime of the Lazy instance. That’s where "LazyEnough" might come in handy. The idea of this class is similar, you initialize it in the same way you initialize Lazy, but with one extra (optional) parameter, TimeSpan. Once initialized, LazyEnough will work almost identically to Lazy, except that each time the TimeSpan elapses, the next call to Value will invalidate the currently memoized value, call the loader Func again, and return the updated value (memoizing it in the process). You should note that this class intentionally doesn’t try to minimize the number of calls to the loader, the idea is that you’re getting a huge gain from just reducing the number of calls to the expensive resource, adding locking code for the rare case where multiple threads will contend to load the same resource is overkill. Anyway, just thought I’d share, hope you enjoy!