Posts Tagged 'values'

Performance of Enum iteration in Java

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
}

Enhanced Links