There are many ways used by performance conscious developers to Cache an Asp.Net Core Application & APIs.
I tried
LazyCache
with one of my ASP.NET Core Application & found a significant performance boost in my Application & APIs as well.
So In this Article, I’m going to Create an Application & use LazyCache to Cache a result of 3000 records Database Table using Entity Framework Core & then I’ll Compare the results with the same query without using LazyCache.
Let’s start by installing LazyCache NuGet Package in our .Net Core project.
Using Package Manager
Install-Package LazyCache
or Using .Net CLI
dotnet add package LazyCache
I have also Created a dummy Database & Added 3000 records using Loop in a Table named as Doctors.
First of all, I’m also going to run a Query for Getting all records from the Doctors Table using EF Core without Caching the Result. Here’s the Code:
public ActionResult GetDoctors() { return Ok(db.Doctors.OrderByDescending(s => s.Id).ToList()); }
For Comparing my Results, I’m Getting the results from Doctors Table with GetOrAdd Method of the LazyCache Library. Here’s my Code fot that:
public ActionResult GetDoctors() { return Ok(cache.GetOrAdd("all-doctors", () => db.Doctors.OrderByDescending(s => s.Id).ToList())); }
I’m going to use my favorite API Load Testing Tool Apache JMeter, for testing my API with 10 Threads.
So after Testing both, with & without Caching
, I’m going to compare my results.
Here’s the Result without Caching
the Query result.
& here’s the result using LazyCache
method GetOrAdd
You can see a significant performance boost in the time taken by the API to get the results of 3000 records from Database with Caching.
Now Let’s compare the Results using Chart.
Here’s the Chart for Query without Caching:
In the above result, you can see that the average time taken by the API with 10 Threads is 289ms.
Now, Let’s see the results using Cache.
The Average Time using LazyCache is 94ms. Which is about 266% less then the Time Taken without Caching.
We have seen a huge difference in the Time taken by the same Query with or without Caching the Result using LazyCache. Without Caching, the average time was about 289ms & running the same query when Cache result it only took 94ms. So, it was a boost of about 266% according to a rough calculation. Using the same way you can Cache your Controller results in your Asp.Net Core Web Application & APIs. Keep in mind, you can not keep your Cache forever. You can also delete your cache manually & Time can also be set for your cache.
Thank you for reading this Article, I hope It will be helpful for you for improving the performance of your .Net Core App.
Related Articles:
Quick Links
Legal Stuff
Social Media