Monday, January 21, 2013

Output Caching in ASP.NET

With output caching, the final rendered HTML of the page is cached. When the same page is requested again, the control objects are not created, the page life cycle doesn’t start, and none of your code executes. Instead, the cached HTML is served. Clearly, output caching gets the theoretical maximum performance increase, because all the overhead of your code is sidestepped. To see output caching in action, you can create a simple page that displays the current time of day. Figure shows this page.

The code for this task is elementary:

public partial class OutputCaching : System.Web.UI.Page
protected void Page_Load(Object sender, EventArgs e)
lblDate.Text = "The time is now:<br />";
lblDate.Text += DateTime.Now.ToString();

You can cache an ASP.NET page in two ways. The most common approach is to insert the OutputCache directive at the top of your .aspx file, just below the Page directive, as shown here:
<%@ OutputCache Duration="20" VaryByParam="None" %>
The Duration attribute instructs ASP.NET to cache the page for 20 seconds. The VaryByParam attribute is also required—but you’ll learn about its effect later on in the “Caching and the Query String” section.

When you run the test page, you’ll discover some interesting behavior. The first time you access the page, you will see the current time displayed. If you refresh the page a short time later, however, the page will not be updated. Instead, ASP.NET will automatically send the cached HTML output to you, until it expires in 20 seconds. If ASP.NET receives a request after the cached page has expired, ASP.NET will run the page code again, generate a new cached copy of the HTML output, and use that for the next 20 seconds.

Twenty seconds may seem like a trivial amount of time, but in a high-volume site, it can make a dramatic difference. For example, you might cache a page that provides a list of products from a catalog. By caching the page for 20 seconds, you limit database access for this page to three operations per minute. Without caching, the page will try to connect to the database once for each client and could easily make dozens of requests in the course of 20 seconds. Of course, just because you request that a page should be stored for 20 seconds doesn’t mean that it actually will be. The page could be evicted from the cache early if the system finds that memory is becoming scarce. This allows you to use caching freely, without worrying too much about hampering your application by using up vital memory.

No comments:
Write comments
Recommended Posts × +