Suppose you have a "simple" enum:
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 wise (memory and time) with using ints?
int day = Day.SUNDAY;
...
public class Day {
public static final int SUNDAY=0;
public static final int MONDAY=1;
}
We have the JIT HotSpot compiler enabled along with other "standard" optimization.
Use enums instead of constant Strings There are obvious benefits to using enums instead of strings for constants because enums enforce validation, but they are generally good for performance: even though HashMap is fast, EnumMap is faster.
Enums are crucial part of every application larger than “Hello World“. We use them everywhere. They are actually very useful: they restrict the input, allow you to compare the values by the reference, provide compile-time checks, and make the code easier to read.
Enums definitely have limits, with the primary (hard) limit around 32K values. They are subject to Java class maximums, both of the 'constant pool' (64K entries) and -- in some compiler versions -- to a method size limit (64K bytecode) on the static initializer.
There may be a slight performance loss for the enum whenever you reference Day.SUNDAY, because the int
constant is a compile-time constant and so can be inlined, whereas the enum
constant requires a getstatic
.
Comparing two ints or two references is of course identical in terms of time required, since you are comparing the references (addresses), not calling .equals()
.
Of course, the performance hit here is minuscule; the only reason to worry about this would be if this is in a performance-critical part of your application and profiling shows that using ints is better. The benefits of enums for maintainability and code correctness far outweigh a slight inefficiency like this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With