Reputation: 1593
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) {
...
}
}
}
Upvotes: 4
Views: 3294
Reputation: 198103
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.
Upvotes: 9
Reputation: 213261
It's a good idea to cache the result of values()
inside the enum itself if you use it multiple times. That's because, every time you invoke values()
method, it creates a new array. So, that is really not required, as you are always going to get the same array elements.
As noted in comments, sharing a cached array will not be thread safe, as other thread can modify the indices in the array, as it's mutable. An option is to wrap the elements in a List<YourEnum>
, and share the list using Collections.unmodifiableList()
.
Upvotes: 8