Why not using a HashMap to get the exact enum instead of compare it one by one?

When I was reading the source code of IoTDB, I found that maybe we can add a HashMap in lots of enum class like TSEncoding to imrpove the time complexity of looking up from O(n) to O(1), like:

private static final Map<Byte, TSEncoding> map = new HashMap<>();

static {

TSEncoding[] array = TSEncoding.values();
for (TSEncoding e : array) {
  map.put(e.type, e);

private static TSEncoding getTsEncoding(byte encoding) {

TSEncoding ret = map.get(encoding);

if (ret == null) {
throw new IllegalArgumentException("Invalid input: " + encoding);

return ret;


Not necessarily.

There’s only 9 entries in the enum. A HashMap is an expensive data structure, and it’s O(1) may well be more than the O(n) for this simple use case, especially considering how is may be used. Odds are that then encoding methods are not universally used, and that the far far most popular ones are determined early in the switch statement that they use.

Arguably, were they to have put the decoding list into a static array and use the offset to look it up, that would be the fastest. But, there may be other reasons they decided to not want to maintain the structure and go that extra mile.

Finally, I don’t know how mainline this lookup is. How often does it happen, how impactful was this decision?

The other benefit is that the current code allows the compiler to potentially make some nice optimizations in what is expressed in simple, clear, idiomatic Java code. Will it? I have no idea, but it has the opportunity. Especially in the dynamic environment of the JIT that can change its mind later on as it gathers statistics over how it’s actually used.