How to Enhance the Performance of a Web Application Using Data Caching and HTTP Caching?
Most Web pages in a Web application typically contain dynamic data that needs to be retrieved from a database. However, executing a database query each time a user places a request can slow down the performance of the application. This problem can be solved by using a concept called data caching.
Data can be cached in a .NET application by using the MemoryCache class. Memory cache allows you to store data that is expensive to regenerate in the form of objects. Each object stored in the memory cache is identified by a key.
Consider the following code snippet that illustrates how to cache data in an application by using the MemoryCache class:
Customer dtCustomer = (Customer)System.Runtime.Caching.MemoryCache.Default.Get(“CustomerData”, null);
if ( dtCustomer == null)
System.Runtime.Caching.MemoryCache.Default.Add(“CustomerData”, getCustomers(), System.DateTime.Now.AddHours(1), null);
dtCustomer = (Customer) System.Runtime.Caching.MemoryCache.Default.Get(“CustomerData”, null);
In the preceding example, the System.Runtime.Caching.MemoryCache.Default.Get() method attempts to retrieve customer data stored with the key name CustomerData. If the cache does not contain any key by this name, the method returns null. In this case, System.Runtime.Caching.MemoryCache.Default.Add() method adds the data to the cache. The first parameter of the Add() function specifies the unique identifier or key of the object that needs to be stored in the memory cache. The second parameter specifies the object that needs to be stored in the cache. In the preceding code, the second parameter is a call to the getCustomer() function. This function returns the object that needs to be stored in the cache.
The third parameter of the Add() function specifies the time when the cache should expire.
The data cache may fetch outdated content, which is stored in memory, instead of taking the latest content from the database. To overcome this problem, you can reduce the amount of time for storing data in the cache. This helps in providing updated content to the users.
You can implement HTTP caching in the browser cache and the proxy cache. Storing data in the browser cache helps remove the need to repeatedly download content from the server. Web browsers frequently check content for updates. If the content is updated in the server, Web browsers download the content from the server to attend to user requests. Otherwise, Web browsers render content from the local cache.
The functionality of the proxy cache is similar to the functionality of the browser cache. However, many users can access the cache in a proxy server, while only one user can access the browser cache at a time.