Hacker News new | past | comments | ask | show | jobs | submit login

I wonder why it doesn't just switch on the ordinal directly.

I don't know how JVM bytecode works, or if it's even possible to assign discontiguous ordinal values, but in C compiled to x86 assembly language, a switch statement on (mostly-)contiguous values can be converted into a jump table. If there are large gaps in the switch values, either you have a lot of wasted space in the jump table, you have multiple jump tables, or you fall back to if/elseif/etc-style code.

It would make more sense to me to assign the contiguous integer values during the construction of the Enum, but maybe that doesn't work when Java 7 code tries to use an Enum compiled with Java 6 or earlier.




> I don't know how JVM bytecode works, or if it's even possible to assign discontiguous ordinal values

That was my first thought as well, but I double checked and the ordinal() method is final, so you're guaranteed not to get anything other than continuous values for your enums.

> in C compiled to x86 assembly language, a switch statement on (mostly-)contiguous values can be converted into a jump table

Ah, this is probably the intention. The JVM can probably optimize the switch. I just checked it, and when there are multiple switch statements in a class only using a few values in an enum, it tries to make them all sequential in the switch, that's why it uses the array. I guess it's just a mistake (or lazy coding) that it always makes the array size TheEnum.values().length rather than how many it's actually going to use.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: