Java Question

JIT compilation

I wonder if constructions like this:

for (Suits suit : Suits.values()) {
// do stuff

will be immediately compiled in this:

Suits[] suits = Suits.values();
for (Suits suit : suits ) {
// do stuff

I do understand, that they will be compiled into second variant after some circles, but would it happen on the first circle?


The first compilation stage is the javac compiler. You should note that when the for-each construct was added as syntactic, no changes to the underlying byte code were needed and these would compile basically the same.

This is long before the JIT optimises the code.

Note: if you are concerned about performance, the last you want to be doing is calling Enum.values() as this creates a new array each time (and a lot of garbage as a result). I suggest you cache this array somewhere it won't be modified.