MemoryCache – AddOrGetExisting Method

MemoryCache provides an easy to use method AddOrGetExisting which provides an easy way to retrive or add data to cache. While it is extremely convenient, it comes off at a cost. Let’s explore it a bit along with alternative.

Note : For the sake of example, let us ignore multi-threading scenarios for the moment.

   public class MemoryCacheRunner
   {
        private MemoryCache _memoryCache;
        private string _uniqueKey = "UniqueKey";
        public MemoryCacheRunner()
        {
            _memoryCache = new MemoryCache("DemoCache");
            _memoryCache.Add(_uniqueKey, new Foo { Name = "Anu Viswan", Age = 36 }, new CacheItemPolicy());
        }
   }

There are two ways we could check if the a particular key exists in the cache and retrieve it (after adding if it is not already present).

Option 1 – Using AddOrGetExisting

public Foo GetFromCacheUsingAddOrGet()
{
    var instance = new Foo { Name = "Anu Viswan", Age = 36 };
    return (Foo)_memoryCache.AddOrGetExisting(_uniqueKey, instance, new CacheItemPolicy());
}

As you can observe, that looks pretty easy and convenient. This is far less code the following approach.

Option 2 – Using Contains/Get

public Foo GetFromCacheUsingContainsAndGet()
{
    if (_memoryCache.Contains(_uniqueKey))
    {
        return (Foo)_memoryCache.Get(_uniqueKey);
    }
    var instance = new Foo { Name = "Anu Viswan", Age = 36 };
    _memoryCache.Add(_uniqueKey, instance, new CacheItemPolicy());
    return instance;
}

That’s definetly a lot more code. But if one was to carefuly observe, Option 2 is infact far more efficient.

In the first approach, you are forced to create an instance of Foo, even if the object exists in the cache. The second approach, however, creates a new instance only if the cache doesn’t contains the specified key.

This could be insignificant when the size of data type is pretty small, but as the size of data increases, one has to be wary of such differences to make your application work optimally.

Leave a comment