Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HotSpot Enum overhead

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.

like image 955
Kevin Kostlan Avatar asked Jan 16 '14 16:01

Kevin Kostlan


People also ask

Is enum faster in Java?

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.

Are enums efficient?

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.

How many values should enum have?

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.


1 Answers

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.

like image 101
Russell Zahniser Avatar answered Nov 11 '22 04:11

Russell Zahniser