Caching in ASP.NET

Introduction

It is a way to store the frequently used data into the server memory which can be retrieved very quickly. Caching increase the performance of the Web applications. Caching is a technique of persisting the data in memory for immediate access to requesting program calls.  

For example

If user is required to fetch the same data from database frequently then the resultant data can be stored into the server memory and later retrieved in very less time (better performance). And the same time the application can serve more page request in the same time (scalability).

ASP.NET provides the following types of caching that can be used to build highly responsive Web applications.

Output caching

Output caching is used for pages and is also known as Page-level caching. All you need to do to enable output caching is to add a directive in your html view of the aspx page. The output directive can be written like this.

@ OutputCache Duration="60" VaryByParam="none"

The above syntax specifies that the page be cached for duration of 60 seconds and the value "none" for VaryByParam attribute makes sure that there is a single cached page available for this duration specified. VaryByParam can take various "key" parameter names in query string.

Fragment caching

Fragment caching is used to cache portions of a response generated by a request. Instead of caching the complete page, some portion of the rendered html page is cached.

Example

User Control used into the page is cached and so it doesn't get loaded every time the page is rendered.

Data caching

Data caching allows developers to programmatically retain arbitrary data across requests. This feature is implemented using the Cache class. Caching is one of the coolest features in Asp.net. Caching enables you to store the expensive data into Cache object and later retrieve it without doing expensive operations. Data Caching can tremendously increase performance since each time the data is requested you can turn to the Cache object rather than going to the database and fetching the result.

Objects can be stored as name value pairs in the cache. A string value can be inserted into the cache as follows:

Cache["name"]="Rohatash";

The stored string value can be retrieved like this.

If Cache("name") IsNot Nothing Then
Label1.Text = Cache("name").ToString()

End
If