I am implementing caching using MemoryCache (.net 4.0) for caching global data which will be used by all users of my website.
My initial approach:
Store a KeyedCollection which would hold a collection of the Customer objects with a key to get a single object. This collection could have up to 250 such objects. Whenever the cache expires, I would rebuild the KeyedCollection and add it to the cache.
New approach
Now, I am thinking why not store each Customer object directly to the cache with the customerid as the look-up key. Therefore, MemoryCache.Default would have upto 250 such Customer objects versus a single KeyedCollection.
Benefits:
- More efficient since I will get the Customer object directly from
the cache without having to perform another look-up on the Keyed
Collection. - I would add a new Customer object to the cache only when it is
requested for the first time. Sort of lazy addition as opposed to
pre-building the entire cache.
Any thoughts on using one versus the other in terms of performance and other factors?
The solution will depend on how often you need to work on the objects as a collection.
Reasons for storing as a collection:
populated, take up more space, as each item in cache would have an
associated
CacheItemPolicy. This case is probably unlikely,however.
available by Linq on collections. (The extension methods are
available, but MemoryCache items are exposed as
KeyValuePair<string,).object>
Reasons for storing individually:
So, compare your likely usage scenario, and choose accordingly. Chances are, unless you are writing lots of
.Where,.Select, etc, calls or have reason to pass around the whole collection, then storing individually is going to be the better choice.