Search code examples
c#.netmstestfactory-patternload-testing

Generic factory: cache vs. repetitive instantination


I have a generic factory which caches an instance before return it (simplified code):

static class Factory<T>
    where T : class
{
    private static T instance;

    public static T GetInstance()
    {
        if (instance == null) instance = new T();
        return instance;
    }
}

I want to replace such approach with non-caching one to show that caching makes no sense in matters of instantiation performance (I believe new object creation is very cheap).

So I want to write a load test which will create a deal, say 1000, of dynamic, runtime-only types and load it to my factories. One will cache, and another - will not.


Solution

  • Sounds to me that your colleague want's to do premature optimizations. Caching objects are seldom a good idea. Instantiation is cheap and I would only cache objects where it's proven that it will be faster. A high performance socket server would be such case.

    But to answer your question: Caching objects will always be faster. Keeping them in a LinkedList or something like that will keep the overhead small and performance should not decrease as the number of objects grow.

    So if you are willing to accept larger memory consumption and increased complexity, go for a cache.