I’ve written a simple microbechmark (dont’ flame me) to have a guess at the cost of using enums vs int constants.
so my enum is defined like this :
public enum Constants { E1(10), E2(20), E3(30)…;
private final int value;
Constants(int value){
this.value = value;
}
}
and the corresponding int constants are :
private static final int I1 = 10, I2 = 20, I3 = 30…
then two loops computing million times things like E1.value + E2.value + E3.value …
and I1 + I2 + I3
now the results :
hostpot client : int constants are twice as fast as Enums.
hotspot server :
-
everything seems precalculated by hotspot (result time near 0) for int constants. I’ll have to write a more tricky bench.
-
Enums are now 4 times faster (making them 2 times faster than the int constants of hostpot client).
==>
I know the poor value of that kind of benchmark, but it shows two things : -
enums are (for me) worth using it to replace int constants, in API like Open GL (thus adding type checking to GL commands).
-
too bad hotspot server doesn’t recognize that constant pattern (an enum IS constant and its member field IS final : should be optimized like those int constants).
Any thoughts ?
Lilian