Search code examples
c#cachingpropertiesmemorycache

Is this an optimal chain in terms of memory management?


We have a system that loads C# poco objects into memory. (Deserialized from data source on disk). They are further cached in ObjectCache (MemoryCache.Default) and exposed via a Repository class. The chain goes like this:

private Dictionary<string, T> itemsDictionary;
    private Dictionary<string, T> ItemsDictionary
    {
        get
        {
            return itemsDictionary ?? (itemsDictionary = RepositoryLoader.Load());        
        }
    }

    private List<T> itemsList;
    private List<T> ItemsList
    {
        get
        {
            return itemsList ?? (itemsList = ItemsDictionary.Values.ToList());
        }
    }

    public List<T> All { get { return ItemsList; } }

RepositoryLoader.Load() - This caches the items in a memory cache as Dictionary...

My question is - as you can see it also goes via 2 cached properties - does it create a duplication on memory consumption or not ? :) Is there a way to optimize this chain ?


Solution

  • If T is a class, having both the itemsDictionary and itemsList means that you have two references to the same memory locations. Assuming the items are each large, e.g. complex objects, this is negligible (4 or 8 bytes per item, depending on if you're running 32- or 64-bit). If the items are structs, however, this means they will be duplicated, and you'll be using double the memory.

    If the memory usage is an issue and you'll only need the ItemsList at certain times, you might want to drop the itemsList field and just make the property generate it on the fly:

    return ItemsDictionary.Values.ToList();
    

    Another option, assuming you have control over the RepositoryLoader functionality, is to write an IDictionary<,> implementation that exposes its Values as, e.g. an IReadOnlyList<T> directly, without recreating the list.