Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is casting enum to int expensive? [duplicate]

Tags:

c#

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?

like image 971
Thomas Avatar asked Jul 24 '13 00:07

Thomas


People also ask

Is type casting costly?

Casting isn't very expensive. Of course, if you have a loop that runs a million times a second it might make sense to avoid casting to save some performance, otherwise it won't really cause performance issues. The real problem with casting is that it's cheating type safety.

Are enums expensive?

Casting from int to an enum is extremely cheap... it'll be faster than a dictionary lookup. Basically it's a no-op, just copying the bits into a location with a different notional type. Parsing a string into an enum value will be somewhat slower.

Can you cast an int to an enum?

You can explicitly type cast an int to a particular enum type, as shown below.

Why is enum faster?

Enum values will take more memory compared to an int constant. Adding a single enum will increase the size of the final DEX file approximately 13x when to an integer constant. This is because each value in an enum class is treated as an object, and each value will take some heap memory to reference the object.


Video Answer


1 Answers

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

like image 89
drz Avatar answered Oct 12 '22 03:10

drz