Applications in ASP.NET are dynamic. This means that user-requested data is often retrieved from the database and then displayed, resulting in increased response time. To overcome this performance overhead, developers employ caching.
Caching is a mechanism that stores frequently accessed data in memory so that when the same data is needed another time, it can be directly obtained from the memory instead of the database. This facilitates high page response time by reducing the time it takes to render the page.
ASP.NET has the following main types of caching:
Page caching
Fragment caching
Data caching
This is also known as output caching. It retrieves data at the page level by storing a copy of the final HTML page in memory. Therefore, the HTML copy is obtained and re-used instead of a new page being regenerated upon the next request.
To use page caching, the OutputCache
directive can be added to the beginning of the .aspx
file:
< %@OutputCache Duration= "60" VaryByParam= "None"% >
The Duration
attribute determines how long the page will be cached. In this case, it will be stored in memory for VaryByParam
is a compulsory attribute used to cache a different page version, depending on the parameter passed to it. As the value passed in the syntax is None
, only one version of the page will be cached in memory.
Note: To know more about other attributes of
OutputCache
, please refer to its. official documentation https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/hdxfb6cy(v=vs.100)?redirectedfrom=MSDN
Also known as partial page caching, this is similar to page caching, except that it provides a mechanism to cache only portions of pages. To do this, we need to encapsulate the section we want to cache in a
In the user control source file, the OutputCache
directive is used. When this file is loaded to the page at runtime, it is stored in the cache. Any subsequent page that uses the same user control will access and retrieve the user control source file from the cache.
< %@OutputCache Duration= "60" VaryByParam= "None"% >
Unlike page and fragment caching, which cache either full pages or a portion of them, data caching stores frequently used objects or data. It does so by storing the result of an SQL request from the database in the cache and directly retrieves the data from the cache for subsequent requests.
ASP.NET consists of the Cache
class and can be used by adding the System.Web.Caching
namespace. The syntax is as follows:
Cache["key"] = value;
To insert objects in the cache, the Cache
class provides the Insert()
method, as shown below:
Cache.Insert(key, value);
Note: Please refer to its
for more overloads of the official documentation https://learn.microsoft.com/en-us/dotnet/api/system.web.caching.cache.insert?view=netframework-4.8 Insert()
method.
Free Resources