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?
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.
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.
You can explicitly type cast an int to a particular enum type, as shown below.
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.
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...
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