Performance of Java Enums?

In a micro-benchmark, yes, checking integer constant equality will be faster than checking enum constant equality.

However, in a real application, let alone a game, this will be totally irrelevant. The things that are happening in the AWT subsystem (or any other GUI toolkit) dwarf these micro-performance considerations by many orders of magnitude.

EDIT

Let me elaborate a little then.

An enum comparison goes like this:

aload_0
getstatic
if_acmpne

An integer comparison for a small integer goes like this:

iload_0
iconst_1
if_icmpne

Obviously, the first is more work than the second, although the difference is quite small.

Run the following test case:

class Test {

    static final int ONE = 1;
    static final int TWO = 2;

    enum TestEnum {ONE, TWO}

    public static void main(String[] args) {
        testEnum();
        testInteger();
        time("enum", new Runnable() {
            public void run() {
                testEnum();

            }
        });
        time("integer", new Runnable() {
            public void run() {
                testInteger();
            }
        });
    }

    private static void testEnum() {
        TestEnum value = TestEnum.ONE;
        for (int i = 0; i < 1000000000; i++) {
            if (value == TestEnum.TWO) {
                System.err.println("impossible");
            }
        }
    }

    private static void testInteger() {
        int value = ONE;
        for (int i = 0; i < 1000000000; i++) {
            if (value == TWO) {
                System.err.println("impossible");
            }
        }
    }

    private static void time(String name, Runnable runnable) {
        long startTime = System.currentTimeMillis();
        runnable.run();
        System.err.println(name + ": " + (System.currentTimeMillis() - startTime) + " ms");
    }
}

and you will find that the enum comparison is slower that the integer comparison, on my machine by around 1.5%.

All I was saying is that this difference will not matter in a real application ("Premature optimization is the root of all evil"). I deal with performance problems on a professional basis (see my profile) and I have never seen a hot spot that could be traced to something like this.


You should care about having nice and readable code before you care about performance. Until your profiling results (no guessing!) show that enums are the bottleneck, forget about performance and use whatever is easier to understand.