Introduction
We normally use Web.Config to store and retrieve common settings for our application, including database connection strings. For dynamic database driven sites, almost for every user control that needs a database connection, there is a lookup on Web.config.
The Catch With Config Files
Like any other File Operations, Config Files also put a need for a (minimal) I/O operation, which on a high traffic site might be a problem on performance. While the file structure is an XML and retrieval is eased with friendly classes like ConfigurationSettings etc, the underlying principle of I/O operation and the cost however remains.
Solution with ASP.NET Caching
ASP.NET comes with an excellent Caching strategy and way the pages, variables and objects are cached is really meticulous. One can also configure how long should an object remain in Cache etc. Here we would present a simpler solution for the abovesaid Config File Reading problem with the help of Cache.
We would first check whether the Item already exists in Cache or not. If yes, then the request for the item is returned from Cache. If the item does not exist in Cache, then an I/O operation to the file is performed and the value is inserted to the Cache. The item is then returned from Cache. For items like ConnectionString, since the cache hit ratio would be very high on a database-intensive web site/application, there is a significant performance gain in terms of atleast config file reading and I/O operation.
Conclusion
I hope the above article would be really useful for ASP.NET/C#/VB.NET developer fraternity worldwide in making effective use of Web.Config and ASP.NET Web Caching strategies.