Introduction to Memorization Pattern

In this article, I am going to discuss about Memorization pattern. This pattern is very helpful to improve performance of the methods that are having complex logic. I will explain about this pattern followed by an example. Most of us use to write some methods that will do complex calculations taking considerable amount of time. Some of these methods might return same result for a given set of parameter's values. So, we can cache those results along with the input values. Next time, if we call that method with same parameter's values, instead of computing the result; it will return from the cached data.

The main theme behind this pattern is to store/cache the results of previous computations so that they can be quickly retrieved without repeated effort.  I am going to explain this pattern with a simple sum of 'n' method.

Scenarios applicable for using this Pattern:

  • If your method is returning constant result for a set of inputs all the time.
  • If your method is having complex logic consuming lot of resources and time.
  • If your method is of recursive nature with constant output for a set of inputs.

Benefits of using this Pattern:

  • Performance can be improved for time consuming methods.
  • Saves utilization of limited resources like memory, CPU time etc.

Implementation:

Create a new console application and name it as MemoizationSample. Now, add the code to program.cs as shown below:

   class Program

    {

        static Hashtable prevResults = new Hashtable();

           

        static void Main(string[] args)

        {

            int n = 0;

            try

            {

                do

                {

                    Console.WriteLine("Enter n value");

                    n = Convert.ToInt32(Console.ReadLine());

                    int sum = SumofNumbers(n);

        Console.WriteLine("Sum of n Numbers: " + sum.ToString());

                } while (n!= -1);

            }

            catch { }

        }

        private static int SumofNumbers(int n)

        {

            if (prevResults.Contains(n))

            {

                Console.WriteLine("From Cache");

                return Convert.ToInt32(prevResults[n].ToString());

            }

            int temp=0;

            for (int i = 1; i <= n; i++)

            {

                temp += i;

            }

            prevResults.Add(n, temp);

            return temp;

        }
    }


In above code, whenever we call SumofNumbers method , we are storing the result of it in a HashTable along with the input value. So, next time if we call this method with same input, instead of computing it again it will return from the HashTable.

Run the application. The output will be as shown below:

1.gif
 

We can use this pattern in methods that will retrieve constant data from the database like zip code, SSN for a given input [like state, person name] etc.

Drawbacks of this Pattern:

  • Consumes time to check whether the result exists or not for a set of inputs in HashTable.
  • Applicable for methods that returns only constant output for a set of inputs all the time.

Suggestion:

It will be very helpful, if this pattern is implemented as a C# language feature by Microsoft team by just adding an attribute like [CacheResult] for methods returning constant results all the time. By this way, we can reduce the code for creating/checking results in HashTable manually.

I am ending up the things here. I am attaching source code for reference. I hope this article will be helpful for all.

Up Next
    Ebook Download
    View all
    Learn
    View all