DEV Community

Cover image for C# - Using Static Caches for Efficiency
Keyur Ramoliya
Keyur Ramoliya

Posted on

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.

Top comments (0)