Would there be difference in speed between
if (myInt == CONST_STATE1)
and
if (myEnum == myENUM.State1)
in c#?
In C# Enums are in-lined to be constants by the compilier anyway, so the benefit is code legibility
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With