Java HotSpot Enum overhead

Suppose you have a "simple" enumeration:

public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } 

And then you use it somewhere:

 Day day = Day.SUNDAY; ... if(day==Day.SUNDAY) {...} 

How does this compare performance (memory and time) using ints?

 int day = Day.SUNDAY; ... public class Day { public static final int SUNDAY=0; public static final int MONDAY=1; } 

We have included the JIT HotSpot compiler along with other "standard" optimizations.

+6
source share
1 answer

There may be a slight performance penalty for listing whenever you refer to Day.SUNDAY, because the int constant is a compile-time constant and therefore can be inline, while the enum constant requires getstatic .

Comparing two ints or two links is, of course, identical in terms of time, since you are comparing links (addresses) without calling .equals() .

Of course, the performance here is negligible; the only reason to worry about this would be if it shows that using ints is better in the performance-critical part of your application and profiling. The benefits of maintainability listings and code validity far outweigh the slight inefficiencies like this.

+6
source

All Articles