Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum values() method efficiency

Tags:

java

enums

Is there any inefficiency in calling the values() function of a specific enum class multiple times?

I have seen instances of existing code where the results of values() are cached for reuse. Is this useful?

public enum Blah {

    private static final Blah [] _myValues = values()

    ...

    public static Blah findBlahFromName(String name) {
        for (Blah blah : _myValues) {
            ...
        }
    }

}
like image 947
Southpaw Hare Avatar asked Sep 17 '25 19:09

Southpaw Hare


1 Answers

Yes, it is inefficient, but there's another way to do it that's not nearly as expensive:

EnumSet.allOf(MyEnum.class);

EnumSet has special wiring into the JDK to allow it to reuse the underlying array.

like image 107
Louis Wasserman Avatar answered Sep 19 '25 11:09

Louis Wasserman