C# MemoryCache for 2 different types of keys? C# MemoryCache for 2 different types of keys? asp.net asp.net

C# MemoryCache for 2 different types of keys?


Go for option #3!

  • For the programmer it is easier to access.
  • It is the fastest solutions (see comments on the other solutions)
  • It is the most memory efficient solution (see comments on the other solutions)

Option #2:

  • You said it yourself.
  • If the cache decides to remove a key, a whole dictionary is removed, resulting in more reloads of the values.

Option #1:

  • You do not have to concatinate string (performance and memeory)
  • Longer key names produce longer compare times.
  • Adding items will be slower because it contains twice as much keys.


I'm not sure what your actual implementation is but be cautious of using sessions in this way with the MVC framework. User identifiers are better left in cookies. Either way, I can see uses to go this route as well on occasion.

I would avoid using dictionaries in the cache in that way. I don't know what type of memory allocation your looking at but it could get real ugly if the server has high traffic and multiple dictionaries. As mentioned above in a comment, you would also have to worry about concurrency issues with dictionaries in that way as well.

The better approach from the options you provided would be to give each namespace it's own instance of the cache.