JDK-6352179 : Modify generated valueOf method for enum (performance enhancement)
  • Type: Enhancement
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 5.0
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2005-11-17
  • Updated: 2010-04-02
  • Resolved: 2005-12-13
Related Reports
Duplicate :  
Description
A DESCRIPTION OF THE REQUEST :
Especially for larger-size enums (more than ten elements), the valueOf method implementation is slow, iterating over all elements of the $VALUES array until an element with matching name is found.

The request is to change the code generated for this method to a hashmap-based lookup, at least for "large" enums.

JUSTIFICATION :
Performance. Example: for an enumeration of 192 countries, the average access times on my machine are as follows:

Generated valueOf method                           2,510 nanoseconds
Hashmap-based getInstance method             92 nanoseconds

For a 64-element enum, the corresponding times are 781 and 87 nanoseconds.
For a 10-element enum, the times are 157 and 76 nanoseconds.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Cache name-element pairs in unmodifiable HashMap.
ACTUAL -
See above.

---------- BEGIN SOURCE ----------
For enum E {...}:

public static E valueOf(String elmName) {
   E elm = _cachedRefs.get(elmName);
   if (elm == null) throw new IllegalArgumentException(...);
   return elm;
}

private static final Map<String, E> _cachedRefs;
static {
   // populate map
}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Write getInstance method for each enum.

Comments
EVALUATION A HashMap is used. The only explanation for the timings reported is that the lazy initialization isn't taken into account. The first reference to valueOf has a cost proportional to the number of enum values. And there is a for loop used for this initialization and perhaps that was mistaken for the search code. If the enum's map is created before timing is started it will be seen that the performance of valueOf is insensitive to the number of values (except for theoretical but slight side effects to do with locality of memory references as they interact with hardware caches, TLBs, etc).
21-11-2005