Enum class performance when array indexing

c++, c++11, enums, performance

Solution

It depends whether the enum value used as an index is known at compile time or passed in a variable.

That is `myArray[(int)myEnum::A]` shall not incur any penalty but `myArray[(int)e]` might, depending on the physical representation of `e` (ie, it might be necessary to "extend" it).

On the other hand, a simple extension is a trivial operation that is unlikely to ever show up as a performance issues: things like branch prediction (in conditionals) and caching are much more important in most applications (for low-level), and at a higher level algorithms matter.

Note: to avoid the extension issue in the runtime scenario, you could define the base type of `myEnum` to be the natural type that is expected for compiler arithmetic, I believe a `ptrdiff_t` would be most appropriate here. It is a big integer though.

Problem

Can I expect to see a performance hit for the casting in this . . ``` enum class myEnum {A,B,C}; myArray[(int)myEnum::A] = 123; ``` Compared to this? ``` enum myEnum {A,B,C}; myArray[A] = 123; ``` I'm leaning towards the new style enum classes for the type safety, but don't want to do it at the expense of performance.

Original source