C# - Using Static Caches for Efficiency

theramoliya

Keyur Ramoliya

Posted on December 22, 2023

C# - Using Static Caches for Efficiency

Tired of repeating calculations? Static caches can be your savior! Here's a quick trick to boost your C# code's efficiency.

For example, We need to calculate the factorial of a number multiple times within our code.

Inefficient approach:

public int Factorial(int n)
{
  if (n == 0)
    return 1;
  return n * Factorial(n - 1);
}

// Repeated calls to Factorial slow down the code
Enter fullscreen mode Exit fullscreen mode

Solution: Implement a static cache to store calculated values.

public class FactorialHelper
{
  private static readonly Dictionary<int, int> cache = new Dictionary<int, int>();

  public static int Factorial(int n)
  {
    if (cache.ContainsKey(n))
    {
      return cache[n];
    }

    if (n == 0)
    {
      return 1;
    }

    int result = n * Factorial(n - 1);
    cache[n] = result;
    return result;
  }
}
Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Reduced overhead: By caching previously calculated values, we avoid unnecessary re-calculations, significantly improving performance.
  • Improved memory efficiency: Caching avoids holding intermediate results in memory, saving valuable resources.

Consider using the ConcurrentDictionary class for thread-safe cache access in multi-threaded applications.

💖 💪 🙅 🚩
theramoliya
Keyur Ramoliya

Posted on December 22, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

C# - Struct Improvements in C# 10.0
csharp C# - Struct Improvements in C# 10.0

December 2, 2023

C# - File-scoped Namespaces
csharp C# - File-scoped Namespaces

December 1, 2023

C# - with expressions
csharp C# - with expressions

December 21, 2023