Memoization Using C#

Posted: April 5, 2020 in .NET, C#
Tags: , ,

Memoization is a technique very commonly used in Functional Programming to improve the performance of a function execution by caching its results. Here, caching helps to avoid the expensive computations of a complex function.

Before getting into the implementation which in my opinion is pretty straightforward to understand let put in few lines on the term itself. This activity of caching the results is similar to memorizing the already computed results but then why “r” is missing and its called memoization ? This is because the term has been derived from memo which is an American English for the Latin word memorandum. So it’s memo-ization.

In order to this we normally write a Higher Order Function (HOF) which accepts the function to be memoized as input and returns a closure of same as type as the input function and wraps it within the logic for caching as shown in the sample below:


Now let’s try to invoke this function. We will use a simple factorial function for memoization here.


We are making three calls to the memoized version of the Factorial function, the last call is made with a repeated parameter.


For the first two calls the function will be executed and the results of the third call are picked up from the cache.


We can write the Memoize function in a much more concise manner as shown below:


We can also make the function thread-safe using ConcurrentDictionary for caching.


  1. Subrata Kundu says:

    Hi Sankarsan,
    This is very helpful topic. Could you please elaborate the maximum size we can keep per entry in the cache.

    • sankarsan says:

      Hi Subrata – The example I have given uses a Dictionary so its memory limit will depend upon the memory allocated to the CLR. However, more sophisticated implementations might need an out of process cache.
      Thanks and Regards-

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.