14.3. Caching

Caching is one of the best and often easiest ways to improve the performance of an application. With caching, a copy of your data is stored in a location that can be accessed very quickly. The idea with caching is that fetching data from the cache should be faster than fetching it from the original data source. Therefore, most caching solutions store data in memory, which is usually the fastest way to get the data. The .NET cache is no exception, and allows you to store frequently accessed data in a special location in the computer's memory.

Usually, the caching principle takes the route displayed in Figure 14-13.

Figure 14-13. Figure 14-13

The application queries for some data — for example, a list of genres from the database. Instead of accessing the database directly, the cache is examined to see if it contains the requested data. If it does, the data is returned from the cache directly. If the data is not stored in the cache yet, it is retrieved from the data source, like a SQL Server database, a copy of the data is stored in the cache for later retrieval, and finally the data is returned to the calling code.

While caching is generally a great solution to improve your application, there are a few drawbacks that you need to be aware of. The following section explains a few common pitfalls you can run into when using caching. The section that follows then shows ...

Get Beginning ASP.NET 3.5: In C# and VB 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.