3.4 Caching Page Output
Another new feature of ASP.NET that should not be overlooked is its support for caching—in particular, output caching. Output caching provides the ability to have the rendered output of a page cached for a specified duration simply and easily. By caching the rendered output in memory, subsequent requests for the page can be delivered substantially faster and with considerably less processor utilization than if the page needs to be re-rendered for each request, which can lead to substantial performance increases. The ASP.NET team has reported page delivery two to three times faster when using output caching. Output caching is available for both ASP.NET pages and ASP.NET user controls.
Not every page can be cached in its entirety. Some pages contain too much dynamic information to be cached as a whole, but even these pages may have portions that seldom change. By moving these static portions into user controls (which also provides the possibility of reuse) and then output caching the user controls, at least some performance benefit can be realized—even for very dynamic pages.
The best part about output caching is its simplicity. In its most basic state, caching the output of a page requires a directive like the following (which you should add directly below the @ Page or @ Control directive):
<%@ OutputCache Duration="20" VaryByParam="None" %>
This directive tells ASP.NET to cache the output of the page for 20 seconds and to return the same cached version of the page for all requests. Example 3-7 demonstrates how to cache the output of a page for 60 seconds and to cache a different version of the page for each different value of the name parameter, when sent as part of the query string of a GET request (for example, http://localhost/aspnetian/OutCache.aspx?name=John). The cache can be varied by form fields in a POST request as well, if desired, by setting the value of the VaryByParam attribute to the name of the form field to vary by.
<%@ Page Language="vb" %> <%@ OutputCache Duration="60" VaryByParam="name" %> <html> <head> <title>Output Cache Demonstration</title> <script runat="server" > Sub Page_Load(Sender As Object, e As EventArgs) lblMessage.Text = "Current time is: " & _ DateTime.Now( ) End Sub </script> </head> <body> <h1>Demonstration of Output Caching</h1> <form id="frmPostBack" runat="server"> <asp:label id="lblMessage" runat="server"/> </form> </body> </html>
As explained in Section 3.1.1 earlier in this chapter, you can also have ASP.NET cache multiple versions of a page on the basis of specific HTTP headers by using the VaryByHeader attribute, or you can cache multiple versions of a user control on the basis of some of its properties by using the VaryByControl attribute. Caching the output of a user control is essentially the same process as that shown in Example 3-7, except that you may not use the VaryByHeader attribute in a user control.