views:

299

answers:

3

Would there be difference in speed between

if (myInt == CONST_STATE1)

and

if (myEnum == myENUM.State1)

in c#?

+7  A: 

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

Rowland Shaw
Perfect. That actually answers quite a few other questions i had! +1
Adam Naylor
You don't happen to know the datatype of such a constant?
Adam Naylor
And even if there was a difference it would rarely if ever be significant.
Brian Rasmussen
@Brian how about in 3D calculations?
Adam Naylor
The datatype? Its underlying type is an int32 by default, if that's what you mean.
jalf
There's nothing magical about 3d calculations. Why would it be more expensive there?
jalf
@Adam: even for 3d calculations I doubt that you'll be spending a significant amount of time doing these comparisons. If these ifs add up to say 1% of the time, you'll not gain a lot by making it go a little faster.
Brian Rasmussen
@jalf - um, because expense is directly proportional to the number of times an operation runs. Do I need to explain the operation count in even a basic 3D simulation? – Adam Naylor (0 secs ago) [remove this comment]
Adam Naylor
Well, it's exactly the same performance. myEnum == myENUM.State1 is translated to int comparison by the JIT. Also, if your enum has fewer options you can change its underlying type to byte or short, and use a smaller data type which usually yields better performance.
configurator
+1  A: 

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

Ray Booysen
+1  A: 

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.

vboctor