Thursday, March 4, 2010

The Types of Caching in ASP.NET

ASP.NET supports three types of caching:

• Output Caching: Caches the output from an entire page and returns it for future requests instead of re-executing the requested page.
• Fragment Caching: Caches just a part of a page which can then be reused even while other parts of the page are being dynamically generated.
• Data Caching: Programmatically caches arbitrary objects for later reuse without re-incurring the overhead of creating them.

Which type of caching you decide to use obviously depends on your situation, but I'll briefly cover them all so you can make an informed decision.

Output Caching
Output caching is the simplest of the caching options offered by ASP.NET. It is useful when an entire page can be cached as a whole and is analogous to most of the caching solutions that were available under classic ASP. It takes a dynamically generated page and stores the HTML result right before it is sent to the client. Then it reuses this HTML for future requests bypassing the execution of the original code.

Telling ASP.NET to cache a page is extremely simple. You simply add the OutputCache directive to the page you wish to cache.
<%@ OutputCache Duration="30" VaryByParam="none" %>
The resulting caching is similar to the caching done by browsers and proxy servers, but does have one extremely important difference... you can tell a page which parameters to the page will have an effect on the output and the caching engine will cache separate versions based on the parameters you specify. This is done using the VaryByParam attribute of the OutputCache directive. The code listing below (a shortened version of output_vary.aspx from the zip file available at the end of this article) illustrates a very simple example of output caching.

<%@ Page Language="VB" %>
<%@ OutputCache Duration="30" VaryByParam="test" %>
<html>
<body bgcolor="#FFFFFF">
<p>
This page was generated at: <strong><%= Now() %></strong>
</p>
</body>
</html>

This piece of code will cache the result for 30 seconds. During that time, responses for all requests for the page will be served from the cache. It also specifies that the caching should vary by the parameter "test". As such, the page will cache a different version for each value of "test" that it is passed and will return the appropriate version based on the value of "test" in the incoming requests.

Fragment Caching
Sometimes it's not possible to cache an entire page. For example, many shopping sites like to greet their users by name. It wouldn't look very good if you went to a site and instead of using your name to greet you it used mine! In the past this often meant that caching wasn't a viable option for these pages. ASP.NET handles this by what they call fragment caching.
Honestly, I find this a little misleading... while you can technically cache part of a page, in order to do so you need to make the section to be cached into a user control and set the OutputCache directive in the new user control. Then you use this control from your dynamic page. The solution works well, but in my mind I think of it as caching a separate mini-page and not really a fragment of a page. I guess it's just semantics, but it is a separate file so it can be a little bit of work to implement.

The caching part is very similar to the code above. Aside from making the section a user control and then using the user control (which we covered in our User Controls lesson) it's pretty boring. There's a sample in the zip file, but I'm not including the code here.

Data Caching
This is the most powerful of the caching options available in ASP.NET. Using data caching you can programmatically cache anything you want for as long as you want. The caching system exposes itself in a dictionary type format meaning items are stored in name/value pairs. You cache an item under a certain name and then when you request that name you get the item back. It's similar to an array or even a simple variable.
In addition to just placing an object into the cache you can set all sorts of properties. The object can be set to expire at a fixed time and date, after a period of inactivity, or when a file or other object in the cache is changed.

The main thing to watch out for with data caching is that items you place in the cache are not guaranteed to be there when you want them back. While it does add some work (you always have to check your object exists after you retrieve it), this scavenging really is a good thing. It gives the caching engine the flexibility to dispose of things that aren't being used or dump parts of the cache if the system starts running out of memory.

Here's a simple example of data caching. Once again it's simply a streamlined version of the script in the zip file.
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
Dim strTimestamp As String
' Retrieve our object
strTimestamp = Cache.Get("SomeData")
' Check to see if we got our object back or not.
' If not, deal with it:
If strTimestamp Is Nothing Then
' Assign a value to our object
strTimestamp = Now()
' Insert into cache:
Cache.Insert("SomeData", strTimestamp, Nothing, _
DateTime.Now.AddMinutes(.5), TimeSpan.Zero)
End If

Caching Rules... Get The Code

If you couldn't tell by now, I really like caching. It's an easy way to make your web pages and applications faster and it really doesn't cost you anything except for a little bit of time to figure out what to cache and for how long to cache it. It does use some memory, but with the price of memory these days, adding a little more (if needed) is a small price to pay for a faster web site.
As usual, the code from this lesson is all zipped up in a nice little file so you can download it and play with it on your own.

0 comments:

Post a Comment