Beware using enum constants as Map keys in performance-sensitive code.

Posted in Java by Dan on December 17th, 2006

I discovered this by accident when replacing some String keys with an enum (in an attempt to reduce the potential for bugs in some code I had written). The change resulted in a big performance hit in a routine that repeatedly queries the HashMap.

In Java 5.0, the implementation of java.lang.Enum.hashCode() is much slower than it needs to be. Furthermore, hashCode() is final, so it can’t even be replaced by something trivial, such as simply returning the ordinal.

The performance problem should be fixed in Java 6.0 but, if you are stuck on Java 5.0, it’s worth keeping in mind when using enum constants to key a map in performance-sensitive code.