TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Memoization

This C# example program uses memoization to optimize repeat calls.

Memoization optimizes repeated method calls.

With the memoization optimization technique, we store the results of a method as it is called. Then we use the lookup table to return them when needed again. We avoid recomputing.

Example. Let's look at an example of a non-memoized function (Lowercase1) and a memoized function (Lowercase2). The first function is much simpler. It calls ToLower on the string argument each time and returns it.

ToLower

The second is more complex. It checks the Dictionary. If it finds a match, it doesn't recalculate the lowercase string. If no match is found, it calls ToLower and stores the result in the Dictionary, then returns the result.

Dictionary

C# program that achieves memoization

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;
    }
}

Output

test test test

In Main, the Lowercase2 method is called twice, but that method only lowercases the string once. This is because the two call sites use the same string argument. We avoid recalculating the result for the second method invocation.

Also: You can memoize multiple argument methods. This can help if there are few variations on most of the arguments.

So: To memoize multiple arguments, you can concatenate a string key and then do a Dictionary lookup.

But: This would only optimize methods that are much slower than string concatenations.

Benchmark. To check the performance advantage, I used a benchmark harness and timed the cost of lowercasing the string "Test" one million times and took the average. The Lowercase2 method (memoization) results in a greater than 2x performance boost.

Caution: The results are not typical because only one argument is passed to the Lowercase methods.

Benchmark Programs

Memoization benchmark result

Lowercase1: 99.62 ns
Lowercase2: 42.08 ns

Arrays. You do not need to use a Dictionary to achieve memoization in a method. For a method that only receives positive integers, you might be able to use an int[] (integer array) lookup table.

Note: This would improve performance over a Dictionary but might lead to edge cases and errors.

Array, Dictionary Test

SICP. Memoization is an old, well-known optimization. As stated in SICP, it can "transform processes that require an exponential number of steps into processes whose space and time requirements grow linearly with the input" (p. 41).

Note: I have found memoization to be one of the more useful optimization techniques in programs.

Tip: Frequently, methods are called repeatedly with the same arguments. Sometimes, memoization can be achieved with just a static field.

Summary. We described memoization as an optimization technique in the C# language. This optimization can greatly reduce the space and time requirements of certain methods that are called repeatedly with the same arguments.

And: It is most effective on programs that repeatedly call a self-contained method with a small number of arguments.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf