11

Since enums are value type and internally integers, is it less expensive to cast them to an int than a cast normally is?

If it is faster, is it because it's value type and not reference type?

Thomas
  • 6,032
  • 6
  • 41
  • 79
  • 6
    Why don't you measure it? – spender Jul 24 '13 at 00:15
  • 2
    Read Jon Skeet's answer here http://stackoverflow.com/questions/3256713/enum-and-performance – lahsrah Jul 24 '13 at 00:16
  • 1
    And after you read Jon Skeet's answer, read Eric Lippert's blog post: http://ericlippert.com/2012/12/17/performance-rant/ – Alden Jul 24 '13 at 00:17
  • I'd venture that your time might be better spent on higher level issues than asking about the (negligible) cost of casting without a particular problem in mind. You should always code for clarity rather than convoluting your code to gain some unmeasured time. You'll end up with complicated code that probably won't run any faster. It's next to impossible to know where your code will "run slow". Don't try and guess. Measure once you've written *correct* code, then act accordingly. – spender Jul 24 '13 at 00:27
  • You either have an unhealthy obsession with premature optimization, or your class is studying something related to that topic currently. If it's the first, learn to write the code first, profile it, and then optimize **the actual bottlenecks in your code** instead of worrying about non-issues like this one. (Anyone who worked for me that wasted time on silly unnecessary optimization of code wouldn't last long; there are productive things to do with that time instead.) If it's the latter, do your homework instead of asking the questions here and waiting for us to answer them. :-) – Ken White Jul 24 '13 at 00:54

1 Answers1

15

No, because of the way it stores the value internally. There is virtually no C# overhead. The overhead in casting is largely due to the amount of code necessary to go from one type to another, does a new object have to be created and allocated memory, etc...

drz
  • 962
  • 7
  • 22
  • 3
    To add to this answer, it looks like the IL to access an array via casted enum vs constant int is absolutely identical. see this gist: https://sharplab.io/#gist:50a591ac8fbbee37727e26a2086531e3 I don't know if it holds true for every scenario, but I assume I cannot be the only one for whom this particular one is relevant. – Daniel Sep 18 '21 at 21:16