Memoization. This is way to optimize repeated method calls in C#. With the memoization optimization technique, we store the results of a method as it is called.
Notes, strategy. When a method is called with the same arguments a second time, we use the lookup table to return them. We avoid recomputing.
An example. This code example shows us how to implement memoization with a Dictionary. We try to avoid recomputing lowercased strings with a cache.
Start Lowercase1 is much simpler. It calls ToLower on the string argument each time and returns it.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string result1 = Lowercase1("Test");
string result2 = Lowercase2("Test"); // Call Lowercase2.
string result3 = Lowercase2("Test"); // Call Lowercase2 again.
Console.WriteLine("{0} {1} {2}", result1, result2, result3);
}
static string Lowercase1(string value)
{
return value.ToLower();
}
static Dictionary<string, string> _lowercase = new Dictionary<string, string>();
static string Lowercase2(string value)
{
string lookup;
if (_lowercase.TryGetValue(value, out lookup))
{
return lookup;
}
lookup = value.ToLower();
_lowercase[value] = lookup;
return lookup;
}
}test test test
Benchmark. To check the performance advantage, I created a benchmark. I timed the cost of lowercasing the string "Test" one million times and took the average.
A summary. This optimization can speed up certain methods. It is most effective on programs that repeatedly call a self-contained method with a small number of arguments.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.