Search code examples
c#asp.netasp.net-mvcmemorycache

C# MemoryCache for 2 different types of keys?


I am using MemoryCache to store key/value pairs in my MVC .Net application.

There are 2 main purposes I am using MemoryCache. One is to store sessions for user ids, and another is to store constants (this is just an example) The keys could theoretically be the same in both cases, so I want some way to separate these 2.

I am thinking of 2 or 3 ways. Which way is superior? Or is there a better alternative?

  1. Each key in the cache will be prepended by a namespace.

    "user_session:1", "user_session:2"
    "constants:1", "constants:2"

  2. Using nested dictionaries as keys.

    There will be a key "user_sessions" whose value will be a Dictionary that maps ids to the session object. There will be a key "constants" whose value will be a Dictionary.

  3. Each "namespace" gets its own MemoryCache instance.

The disadvantage with #2 is that when I want to get the value belonging to a user ID, I need to first get the dictionary, then get the value for a key in that dictionary. Which means I need to store the dictionary in memory.

IE:

Dictionary<string, string> userSessions = MemoryCache.Default["user_sessions"]
object session = userSessions.get("1");

Solution

  • 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.