Friday, June 5, 2009

ASP.NET Caching

Caching

Caching is the process of storing frequently used data, usually data that is costly to generate, for reuse. Typically this data is stored in memory since retrieving data from memory is much more efficient than retrieving the data from other locations, such as a database.

ASP.NET has several facilities for supporting caching: a Cache API for storing arbitrary data and an Output Cache used to store frequently requested Pages.

Let's discuss a quick example.

A catalog used on an e-commerce site might only change once a week. An ASP.NET Web application could be built that provides a front-end interface for that catalog, allowing customers to purchase products. When a customer is simply browsing the catalog, the system is making (in most cases) network calls to a back-end database server. The database server is also doing calculations on the data, such as a join query, and returning results.

This type of configuration is quite common, be it a catalog or some other type of commonly requested data from a database. However, the design in the above example can be improved upon. We know that the data in the database only changes once a week, and we know that there are several performance costs associated with retrieving the data:

  1. Executing of the ASP.NET code to make the database request.
  2. Use of the network for the Web server to communicate with the database server.
  3. Work done on the database server to compile and execute the query (or simply execute stored procedure).

Caching allows us to eliminate much of the above work and improve the performance and scalability of our application. We can improve performance by caching the results and serving them statically (versus dynamically on each request) and our scalability increases since we're using fewer resources to service each request.

Beta 1 of ASP.NET introduced the Cache API as well as Page output caching, which uses the Cache API. Let's discuss these two features in more detail.

Cache API

Storing frequently requested data in memory is nothing new for ASP developers. We've had two types of objects that solve this problem:

  • Session objects
  • Application objects

Session is used to store per-user data across multiple requests. There have been some changes for Session in ASP.NET but most of these changes are application level changes and don't affect the way Session is used, that is, it's still a simple key/value pair.

The Application object from ASP is also carried forward to ASP.NET, and it to remains identical in function (key/value pairs). For example, we could write the following in either ASP or ASP.NET:

see full detail:

http://msdn.microsoft.com/en-us/library/ms972379.aspx

No comments: