重复调用 ConfigurationManager.AppSettings 来获取 appsetting 值会出现性能问题吗?
我正在开发一个代码库,其中散布着许多相同的 ConfigurationManager.AppSetting 调用。
这听起来像是可能的性能问题吗?
或者因为数据非常小所以微不足道并且不“昂贵”?不断返回文件以获取数据,或者 .NET 运行时是否缓存文件/值/调用?
如果这不是性能问题,是否只是访问应用程序配置值的一种杂乱的方法,是否应该重新考虑以更清晰和一致的方式访问设置?
I'm working on a code base that has a lot of identical ConfigurationManager.AppSetting calls scattered throughout.
Does this sound like a possible performance issue?
Or because the data being very small is trivial and not 'expensive'? Constantly going back to the file to get the data, or does the .NET runtime cache the file/values/calls?
If this isn't a performance issue is it just a disorganized approach to accessing the application configuration values, and should just be re-factored to be cleaner and consistent implementation of accessing the settings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想说这更多的是代码可维护性问题而不是性能问题。对
AppSettings
进行简单的字典查找不会成为问题,除非您有代码尝试在运行数百次的循环中对AppSettings
执行查找。这样的代码肯定会导致性能问题。但更重要的是,您的代码库中将拥有ConfigurationManager.AppSettings["MyKey"]
。您正在引入一个神奇的字符串。如果您必须更改配置文件中的密钥,则必须在所有项目中进行彻底的搜索和替换。此外,我们通常会根据 appSettings 中存储的值做出一些决定。它并不总是直接读取并按原样使用该值。有时你会根据价值做出决定。例如,您可能会在数百处重复这个逻辑。现在假设您需要在那里添加另一个条件:
这会变得混乱。你的代码开始发臭。
因此,我始终建议我的开发团队永远不要在代码中的任何位置使用
ConfigurationManager.AppSettings
。使用一些静态类来读取配置值,并将所有此类决策预先缓存到单个变量中。例如,这不仅性能更好,而且代码的可维护性和可扩展性也很高。
I would say it's more of the code maintainability issue than performance issue. A simple dictionary lookup on
AppSettings
isn't going to be a problem unless you have code that tries to perform lookup onAppSettings
in a loop that runs say hundred times. Surely such a code will cause performance problem. But even more important is you will haveConfigurationManager.AppSettings["MyKey"]
throughout your codebase. You are introducing a magic string. If you have to change the key in your configuration file, you will have to do a thorough search and replace in all your projects. Moreover, we usually make some decision based on the value stored in appSettings. It's not always straighforward read and use the value as-is. Sometimes you take decision based on the value. For ex,You might be repeating this logic in hundred places. Now let's say you need to add another condition there:
This gets messy. Your code starts to stink.
So, I always recommend my dev team to never use
ConfigurationManager.AppSettings
anywhere in the code. Use some static class where you read the configuration values and all such decisions are precached into a single variable. For ex,This is not only better in performance, but also highly maintainable and extensible code.
这里有几件事。
A few things here.