Florence Blogspot about asp.net tutorials and web design and web development

Wednesday, February 6, 2008

Improve your ASP.NET Site performance with Caching

Improve your ASP.NET Site performance with Caching

In this article, I would like to share my experience and knowledge about ASP.NET Caching and how it can improve your website performance. As you all might know that performance is key requirement for any application or piece of code that you develop. For mission critical website, Caching is the way to go to significantly enhance your web response times. Caching is the process of storing frequently used data on the server to fulfill subsequent requests.You will discover that grabbing data or objects from memory is much faster than recreating the web pages or items contained in them from scratch.

When and Why use Caching

A Proper use and fine tune of caching approach of caching will result on better performance and scalability of your site. However improper use of caching will actually slow down and consume lots of your server performance and memory usage.

Good candidate to use caching is if you have infrequent chance of data or static content of web page.

For example, Stock market website displaying 20 minutes delay data can actually use data caching to store the data, so that it can reduce database call every time the user refresh the page.

Another good example would be using Partial page caching to store some of the infrequent or static content. If you have websites that show lots of information or features, you can actually group the static or infrequent change content into user controls and then set the Caching for that particular user controls. You can set the amount of time when the caching expires so that it will load new data from database.



Type of Caching

1. Output Caching (Page Caching)

The most easiest and simple caching that you can implement. Good for caching the static page that is accessed frequently. You can copy and paste the code below on your ASP.NET page.

Duration attribute specifies how long in seconds that the page will be held in the memory. When the cache expired, the asp.net engine will automatically reload and refreshes the page again. If the page never change, you can actually set the duration to very long period.

Valid Parameters for OutputCaching

1. VaryByParam

The VaryByParam attribute is for caching different type of page based on the HTTP Post or HTTP Get Protocol
e.g You can cache dynamic content based on different query string provided.



In this case, asp.net engine will cache the dynamic page based on the different query string provided. If your page is generating different content based on the query string, then you need to put that in the output cache directive or else all your users will see the same content.

If you want to cache a new version of the page based on any differences in the Query String parameters, use VaryByParam = "*" as in the following code.


2.VaryByControl
VaryByControl can be used to cache the usercontrol inside your page. For example you can cache a user control that contains ComboBox that render all the country name in the world. And perhaps those country data is retrieved from database, this will make significant performance for page loading time.

3.VaryByCustom
To make the Cache object even more flexible, Microsoft built in the ability to cache the page based on a string, which is then controlled from the actual code of the application

It does have one "out of the box" property, Browser. When VaryByCustom is set to Browser the page is cached every time a different browser agent and major version number requests the page.

If you like to have your own set of Caching rule ,then you might need to tweak some of the code in global .aspx
For e.g You might need to differentiate caching content for different set of users based on cookies called Language. Then you need to copy and paste the following code in your global.asax file.

Code in VB.NET

Overrides Function GetVaryByCustomString(ByVal context as HttpContext,_
ByVal arg as String) As String
If arg.ToLower() = "cookies" Then
Dim cookie as HttpCookie = context.Request.Cookies("Language")
If cookie isNot nothing Then
Return cookie.Value
End if
End If
Return MyBase.GetVaryByCustomString(context,arg)
End Function


Code in C#
public override string GetVaryByCustomString(HttpContext context, string arg)
{
if (arg.ToLower() == "cookies")
{
HttpCookie cookie = context.Request.Cookies["Language"];
if (cookie != null)
{
return cookie.Value;
}
}
return base.GetVaryByCustomString(context, arg);
}


After that , set the VaryByCustom attribute to "cookies" in your OutputCache directives.
By doing that you will generate different set of caching based on the Client languages cookies. This is just one of the example of doing VaryByCustom caching, you can actually create your own set of caching rules by differentiating caching based on user logged on, and etc.

4.VaryByHeader
Varies cache entries based on variations in a specified header

2. Partial Page (UserControl) Caching.

Similar to output Caching, partial page caching allows you to cache certain blocks of your website.You can for example only cache the center of the page. Partial page is achieved with the caching of the user controls. You can build your ASP.NET pages consisting of numerous user controls and then apply output caching on the user controls you select. This will caches only parts of the page that you want and leaving other parts of page outside the reach of caching.
This is very nice feature and if it done correctly, it can lead to pages that perform better.

Note :
Typically UserControls are placed on multiple pages to maximize reuse. However, when these UserControls (ASCX Files) are cached with the @OutputCache Directive , they are cached on per page basis.That means even if a User Control outputs the identical HTML when placed on pageA.aspx as it does placed on pageB.aspx,its output is cached twice.
You can prevent this to happen by adding Shared = true in the output cache directive.


By putting Shared attributed, the memory savings can be surprisingly large.
If you have an ASCX User control using the OutputCache directive,remember that User Control exists only for the first request.

3. Data Caching

Output Caching and Partial Page caching is useful if you want to cache the output of the page. However if you like to cache DataSet object or any Collections object, you can use Data Caching to implement that.

ASP.NET has one class called Cache Object to start caching specific data items for later use on particular page or group of pages. The cache object enables you to store everything from simple name/value pairs to more complex objects like datasets and entire .aspx pages.

VB.NET

Cache("MyDataSet") = myDataSet;

C#

Cache("MyDataSet") = myDataSet;To retrieve the data from the cache, you can use the code below.

VB.NET



Dim ds as New DataSet
ds = CType(Cache("MyDataSet"),DataSet)

C#
DataSet ds = new DataSet();
ds = (DataSet) Cache["MyDataSet"];



Conclusion
As we've just seen, caching Web pages with ASP.NET is amazingly easy, accomplished with a simple line. With this glimpse of ASP.NET's caching abilities, you can improve your Web application's performance. But remember Caching in ASP.net is a trade off between CPU and memory. How hard is it to make this page versus whether you can afford to hold 200 versions of it. If it's only 5KB of HTML, a potential megabyte of memory could pay off handsomely versus thousands and thousands of database access. Every page of request served from the cache saves you a trip to the database.

No comments:

Search