On Java, the common way to iterate over an Enum is simply:
for (MyEnum d : MyEnum.values()) { // do something }
But you have to know that every time you call to values() method on an Enum, the JVM must to create a copy of the internal array of the Enum values (to prevents users to change its values). This causes a significant performance loss. So, in case that your applications calls recurrently to the Enum.values() method, you can do something like this:
public enum MyEnum { A, B, C; // sample values public static MyEnum[] values = MyEnum.values(); }
Then, iterate the enum values by using the values variable:
for (MyEnum d : MyEnum.values) { // do something }
Hi,
For Java 7, I think that this tips isn’t necessary.
I looked at http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9
and I saw that values() is static.
/**
* Returns an array containing the constants of this enum
* type, in the order they’re declared. This method may be
* used to iterate over the constants as follows:
*
* for(E c : E.values())
* System.out.println(c);
*
* @return an array containing the constants of this enum
* type, in the order they’re declared
*/
public static E[] values();
am I correct ?
driu:
The javadoc you posted says nothing about how it handled the internal array of the Enum values (if it is cached or not). Also, this javadoc is exactly the same as the Java version 5 (http://docs.oracle.com/javaee/5/api/javax/persistence/EnumType.html#values%28%29). Yet, it would be good to do a test in Java 7 (I have not done) to see if the internal behavior of Enums changed from that version.
Regards
Thanks for your answer,You’re right, there is nothing about how it handled the internal array.
I have 2 other questions :
– Where do you see that the JVM must to create a copy of the internal array of the Enum values (Official doc ?) ?
– If we have an Enum with few values, does-it really causes a significant performance loss ?
Thanks,
driu:
– If the JVM returns the internal array of an Enum, an user can change its values, causing an inconsistency system. To safe this, it must create a copy of this one. Also, if you make a test with both alternatives (by using values() directly or using the static variable as a cache) you will see how response times change.
– Obviously. You must consider the number of the Enum entries and how often its called the values() method. In some cases, it is no neccesary to caching the Enums values.
thanks