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) {
...
}
}
}
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()
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.