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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay