Reduced code size using EnumSet

Issue #26 closed
Markus KARG created an issue

Sometimes it happens that one writes code like if (status == A || status == B || status == C) which easily gets hard to read with many status to check.

A solution which not only reduces code size and improves readability, but also provides potentially faster execution due to eager compilation of shared code and using a bit-mask (!) internally, is the use of EnumSet:

if (EnumSet.of(A, B, C).contains(status)

or even better...

static EnumSet ABC = EnumSet.of(A, B, C);
if (ABC.contains(status))

Why is this faster? The trick is twofold. First, there is no need for the JVM to load and interpret lots of custom boolean terms, but it can simply invoke the static enum set. Second, an EnumSet is solely a bitmap. That bitmap is and'ed with the the bitmap provided to contains() or containsAll() ins a single operation, as it fits into one register. In comparison, the binary term has to be executed sequentially, which means many operations.

In reality, a performance gain will only be measurable in scarce cases, as modern CPUs are lightning fast, and the typically the same bitmap pattern is only used seldomly. Nevertheless, it is a good pattern due to its readability, compared to rather long boolean chains.

Comments (4)

  1. Christian Schudt repo owner

    Not sure, if I found all such enum comparisons. If you find another one, feel free to reopen.

  2. Log in to comment