Managing data efficiently is crucial for maintaining application performance and scalability in modern software development. In Memory Caching Technique is one powerful technique for optimizing data retrieval, which stores frequently accessed data in memory for rapid access. In C#, the MemoryCache class provides a convenient way to implement caching within applications. In this article, we’ll explore how to initialize and utilize MemoryCache
to improve data retrieval performance.
Benefits of In Memory Caching
Pros
- Reduce database calls and IO Operations
- Increase the performance of the code
- Time Bound data validity
- Saves Cost for throughput-based databases which bill by Request Units (RU)
Cons
- Increase maintenance
- Need to Create a Unique Combination of Keys for complex query
- Data may go out of Sync if changes happen in the database from other source
Initializing MemoryCache
To begin caching data in C#, we first need to initialize two static readonly variables: cacheEntryOptions
and cache
. These variables allow us to define caching options and instantiate a MemoryCache
object, respectively.
private static readonly MemoryCacheEntryOptions cacheEntryOptions = new MemoryCacheEntryOptions();
private static readonly IMemoryCache cache = new MemoryCache(new MemoryCacheOptions())
The cacheEntryOptions
variable represents the options for caching entries, such as expiration policies, while the cache
variable holds the cached data using the MemoryCache
class.
Caching Data
Once the caching infrastructure is set up, we can start caching data based on certain conditions. The typical workflow involves checking if the desired data is already cached. If found, we retrieve it from the cache. Otherwise, we perform the necessary operation to generate the data, cache it, and then return it.
string key = "key";
if (cache.TryGetValue(key, out string cachedValue))
{
// Use the cachedValue or return as per the use case
}
else
{
// Perform your operation to get Response/data
string response = GetResponse(); // Assuming there's a method to get the response
cachedValue = response;
cacheEntryOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(20); // Set Memcache duration for 20 minutes
cache.Set(key, cachedValue, cacheEntryOptions);
}
In the above code snippet, we first attempt to retrieve the cached value using a specified key. If the value is found in the cache, we use it directly. Otherwise, we perform the necessary operation (e.g., fetching data from a database or external API) to obtain the response/data, cache it with a defined expiration time, and then return it.