dotnetster
dotnetster

Reputation: 1611

.Net System.Runtime.Caching.MemoryCache - Store a single collection or individual custom objects?

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:

  1. More efficient since I will get the Customer object directly from the cache without having to perform another look-up on the Keyed Collection.
  2. 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?

Upvotes: 3

Views: 3176

Answers (1)

Mike Guthrie
Mike Guthrie

Reputation: 4059

The solution will depend on how often you need to work on the objects as a collection.

Reasons for storing as a collection:

  • Storing each object individually, if all 250 objects are always populated, take up more space, as each item in cache would have an associated CacheItemPolicy. This case is probably unlikely, however.
  • You would not have strongly typed extension methods made available by Linq on collections. (The extension methods are available, but MemoryCache items are exposed as KeyValuePair<string, object>).

Reasons for storing individually:

  • You are only or mostly going to be working one a single object at a time.
  • You want each object to be created and removed from cache based on its own frequency of usage, rather than that of a whole collection.

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.

Upvotes: 3

Related Questions