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. This 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 ...

Get ASP.NET in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.