枚举评估和整数之间的性能比较

发布于 2024-07-10 20:38:24 字数 151 浏览 9 评论 0 原文

之间的速度会有差异吗?

if (myInt == CONST_STATE1)


if (myEnum == myENUM.State1)

C#

Would there be difference in speed between

if (myInt == CONST_STATE1)

and

if (myEnum == myENUM.State1)

in c#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

岁吢 2024-07-17 20:38:24

在 C# 中,无论如何,枚举都会被编译器内联为常量,因此好处是代码易读性

In C# Enums are in-lined to be constants by the compilier anyway, so the benefit is code legibility

眉目亦如画i 2024-07-17 20:38:24

使用枚举时要小心的是不要使用任何需要反射的操作(或谨慎使用它们)。 例如:

  1. myEnumValue.ToString()。
  2. Enum.Parse()
  3. Enum.IsDefined()
  4. Enum.GetName()
  5. Enum.GetNames()

对于常量,不存在执行任何需要反射的操作的选项。 但是,对于枚举来说确实如此。 所以你必须小心这一点。

我见过配置文件报告,其中与枚举验证/反射相关的操作占用了高达 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:

  1. myEnumValue.ToString().
  2. Enum.Parse()
  3. Enum.IsDefined()
  4. Enum.GetName()
  5. Enum.GetNames()

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.

云雾 2024-07-17 20:38:24

另外,我不确定您是否需要担心这一点。 这听起来确实像是过早的优化。 我确信在任何系统中,都存在比枚举比较更大的瓶颈。 :)

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. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文