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());


Join the conversation! Your thoughts help the community grow.