I wonder if adding an Enum
a static Holder is always a better implementation over iterating values on "get" Enum method (or similar for getting specific Enum value).
For example for Spring HttpStatus current implementation :
HttpStatus(int value, String reasonPhrase) {
this.value = value;
this.reasonPhrase = reasonPhrase;
}
public static HttpStatus valueOf(int statusCode) {
for (HttpStatus status : values()) {
if (status.value == statusCode) {
return status;
}
}
throw new IllegalArgumentException("No matching constant for [" + statusCode + "]");
}
Can be optimized with:
private static class Holder {
private static Map<Integer, HttpStatus> enumMap = new HashMap<>();
}
HttpStatus(int value, String reasonPhrase) {
this.value = value;
this.reasonPhrase = reasonPhrase;
Holder.enumMap.put(value, this);
}
public static HttpStatus valueOf(int statusCode) {
return Holder.enumMap.computeIfAbsent(statusCode, statusCode -> {
throw new IllegalArgumentException("No matching constant for [" + statusCode + "]"); });
}
Code optimization:
The loop version has linear time complexity (every request to get value) whereas the version using a HashMap has a time complexity of O(1).
Can this optimization have a flaw I'm missing?