Question

Would there be difference in speed between

if (myInt == CONST_STATE1)

and

if (myEnum == myENUM.State1)

in c#?

Was it helpful?

Solution

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

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top