New Adventures in Software


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.

Want more articles like this? Subscribe to the feed.

3 Responses to 'Beware using enum constants as Map keys in performance-sensitive code.'

Subscribe to comments with RSS or TrackBack to 'Beware using enum constants as Map keys in performance-sensitive code.'.


  1. on May 14th, 2007 at 4:06 pm

    Why not use the EnumMap? It promises better performance than the regular HashMap by using the ordinal value and an underlying array.

  2. Dan said,

    on May 14th, 2007 at 6:56 pm

    Definitely, that occurred to me after I originally posted this. The hashcode() performance is still poor, it’s just not such a problem if you use EnumMap.

  3. Anjan Bacchu said,

    on May 15th, 2007 at 4:38 am

    hi there,

    I actually did exactly the same “mistake” but did NOT notice any big performance change. This was for a swing app — the reason I did that was to make a LARGE if () else if () block more readable(by making it a switch/case) block.

    Also, almost immediately, I replaced with EnumMap — probably that was the reason why I(nor the users/testers) we did not notice a big performance change.

    Unfortunately, I don’t have that code with me as of now and I will have to ask my ex colleagues to investigate it.

    Can you specify which version of java u used ?

    BR,
    ~A

Leave a Reply