Sunday, July 12, 2009

ASP.Net - Caching static files (images, css, js, etc. ) to improve performance

Recently we had a need for performance improvement in our large web application. With one simple solution, we could achieve great performance improvement. We just implemented static file caching. We cached all static files like images in our web application which resulted in less calls to the server with each request and improving performance in many folds.

To understand the impact of static files with your application, you might want to use a utility like fiddler or microsoft network monitor. Hit your page and see what files are actually request and transmitted from server each time. In our case, we had these logos, menu images, css files, common js files etc. received each time a page request is made. After logging these calls for a simple use case, we could see how this is hampering the performance.

There is a nice article explaining different ways to achieve static file caching in ASP.Net. We used http module to listen to the requests and append/edit some headers to do the caching part. Without touching thousands of pages in the app and without even touching the IIS (which would be difficult to do for 1000+ existing customers hosting it in their network) we could improve the performance considerably. If you are looking for the actual code that made it work, you might want to dig into the HttpContext.Response.Cache class. You might find the following methods useful:

SetValidUntilExpires(true);
SetCacheability(HttpCacheability.ServerAndPrivate);
SetMaxAge(TimeSpan.FromMinutes(expirationTime));
SetExpires(DateTime.UtcNow.AddMinutes(expirationTime));

Did you find this tip useful? Or do you know of any other tips to improve performance of ASP.Net applications? Do share your views by posting comments.

No comments: