Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance comparisons betweeen enum evaluations and ints

Would there be difference in speed between

if (myInt == CONST_STATE1)

and

if (myEnum == myENUM.State1)

in c#?

like image 824
Adam Naylor Avatar asked Jan 02 '09 12:01

Adam Naylor


2 Answers

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

like image 79
Rowland Shaw Avatar answered Dec 14 '22 19:12

Rowland Shaw


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.

like image 42
vboctor Avatar answered Dec 14 '22 20:12

vboctor