枚举评估和整数之间的性能比较
之间的速度会有差异吗?
if (myInt == CONST_STATE1)
和
if (myEnum == myENUM.State1)
C#
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
之间的速度会有差异吗?
if (myInt == CONST_STATE1)
和
if (myEnum == myENUM.State1)
C#
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
在 C# 中,无论如何,枚举都会被编译器内联为常量,因此好处是代码易读性
In C# Enums are in-lined to be constants by the compilier anyway, so the benefit is code legibility
使用枚举时要小心的是不要使用任何需要反射的操作(或谨慎使用它们)。 例如:
对于常量,不存在执行任何需要反射的操作的选项。 但是,对于枚举来说确实如此。 所以你必须小心这一点。
我见过配置文件报告,其中与枚举验证/反射相关的操作占用了高达 5% 的 CPU 时间(在每次调用 API 方法时都进行枚举验证的场景)。 通过编写一个类来缓存所使用的枚举类型的反射结果,可以大大减少这种情况。
话虽如此,我建议根据从设计角度来看是否有意义来决定使用枚举还是常量。 同时确保团队了解涉及反射的操作对性能的影响。
The thing to be careful about when using Enums is not to use any of the operations that require reflection (or use them with care). For example:
In case of constants the option of doing any operations that require reflection doesn't exist. However, in case of enums it does. So you will have to be careful with this.
I have seen profile reports where operations relating to enum validations / reflections took up to 5% of the CPU time (a scenario where enum validations were done on every call to an API method). This can be greatly reduced by writing a class that caches the results of the reflection of the enum types being used.
Having said that, I would recommend making the decision of using enum vs. constant based on what makes sense from a design point of view. This is while making sure that the team is aware of the performance implications of the operations involving reflection.
另外,我不确定您是否需要担心这一点。 这听起来确实像是过早的优化。 我确信在任何系统中,都存在比枚举比较更大的瓶颈。 :)
Also, I'm not sure you need to be worried about this at all. It does sound like premature optimisation. I'm sure that in any system, there are bigger bottlenecks than enum comparisons. :)