Caching of WebConfigurationManager.AppSettings?

2020-08-10 08:05发布

问题:

I have a lot of requests that read my Web Config file

variable = WebConfigurationManager.AppSettings["BLAH"]

Do WebConfigurationManager.AppSettings read from disk each time, or is it cached in memory?

If it's read from disk each time then I guess I will need to move the variable to a static variable so as to improve my app performance.

回答1:

Configuration settings are cached in memory and web.config is not parsed every time you call this function.



回答2:

I was just researching this subject. And it is true that the configuration settings are cached in memory.

However, you can still see a performance benefit by storing the values in static variables as you mention (and as described here). This is because the AppSettings collection is a NameValueCollection. And so every time you reference an AppSetting it has to search the collection which is a O(n) operation.

Albeit, this is probably a rare thing that this would ever be a bottleneck of your application. But one could imagine a scenario with a tight loop referencing a single value in AppSettings, where the AppSettings collection is very large. In that case you might as well cache the value in some fashion, even if it's simply storing it in a local variable before starting your loop.