Wednesday, 23 December 2009

Caching using static members

There is an interesting post that has proved useful covering the use of static lists in static class to cache.

   public static partial class Store
   {
        private static StringDictionary cacheCollection;

        // The static constructor is used to load the list, static
        // constructor is called only once
        // If the 'collection' is to be modified after load, 
        // then careful consideration is required around thread safety!
        static Store()
        {
            LoadCacheCollection();
        }

        private static void LoadCacheCollection() {
            
            cacheCollection.Add(...);
            .
            .
            return;
        }

   }

This method could be refactored such that the code required to manage the collection exists in a base assembly and the collection itself and anything specific exists in an assembly inheriting from the base.
Note: A static variable can be copied to an instance variable without extra memory being allocated (i.e. the pointer is moved, without a copy being made).

No comments: