views:

352

answers:

3

Looking at implementing caching for some common lookup data in an asp.net web application.

In the past, I've created a singleton that creates a bunch of hashtables, which have public accessors. This works pretty well for read-only data that never changes.

I've done a bit of looking into the System.Web.Caching, but it doesn't seem to offer any benefits over the singleton approach. We're not using SQLServer, so we wouldn't be able to take advantage of the SQLCacheDependency for the rare cases where the data might change.

Anyone have experience with either of these alternatives? Or have a better suggestion?

+3  A: 

One benefit to the System.Web.Caching is that the memory is stored in the app pool. This is handy because it is very easy to setup memory/processing limits on application pools.

I ran into this when we were stress testing our application (Each user task requires costly computation). As we added more and more users, the cache took up all the available memory. Once we setup a memory limit on the app pool, everything took care of itself. The Cache has LRU algorithms to manage memory.

I don't know if the data in your cache is dependent on load, but if it is, this is a handy benefit.

jwmiller5
The memory used by singleton objects is also stored in the app pool.
Seth Reno
+1  A: 

I can't speak to the benefits of System.Web.Caching since, like you, I've typically implemented singleton instances of a lookup table data structure. The singleton class also exposes an InvalidateCache() method to handle the rare cases where data might change.

If you're building a business object library for use in both asp.net and, for example, winforms then you might decide to avoid using System.Web.Caching.

The Business Object framework which I use provides a base class for lookup tables called NameValueListBase<TKey, TValue>. This generic base class provides strongly typed helper methods. You could develop a similar base class and expose your own helper methods as opposed to just exposing an instance of System.Collections.Generic.Dictionary.

The Business Object framework to which I refer is called CSLA.Net and is explained in great detail in Expert C# 2008 Business Objects. There is also a version of the book available for VB.Net.

Ken Browning
A: 

I have experience with both. I prefer the singleton pattern for the following reasons:

  1. It's not tied to asp.net
  2. It allows you to use the lookup in the bisiness layer to validate or whatever.
  3. It's easier to refactor if the lookup becomes more complicated and you decide not to cache it.
Seth Reno