Search code examples
javaoptimization

Do Java compilers commonly precompute hashcodes of final fields?


I have a HashMap-intensive Java program in which several classes have hashcodes computed from final fields. For example:

public class Foo {
    private final int bar;
    private final String zot;

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + bar;
        result = prime * result + zot.hashCode();
        return result;
    }
}

It's possible for the compiler to observe that the hashcode cannot change after object initialization, and precompute it into an additional private final field. Do current Java compilers do this, like the one in Oracle JDK 7? I could disassmble the .class file, but then the JIT may also do this kind of optimization at runtime and I would not see it there. Anyway, I'm interested in other cases besides this one, so it would be great to find a general approach for identifying any optimizations the compiler does automatically.


Solution

  • Do current Java compilers do this, like the one in Oracle JDK 7?

    The javac does almost no optimisations.

    I could disassmble the .class file,

    You might not like what you see in terms of optimisations. ;)

    but then the JIT may also do this kind of optimization at runtime and I would not see it there.

    If the JIT did optimise this, you wouldn't see it and in fact it doesn't do this. This is why String caches it's hashCode() at runtime, explicitly in code.