BooleanFieldEnum
has 2000
enum constants with a boolean
field each (initialized on constructor). The isSet
returns the value of this field.
SwitchEnum
has 2000
enum constants with no fields. The isSet
method does a switch
on this
(referring to the enum instance).
Test setup
# JMH version: 1.21
# VM version: JDK 11.0.2, Java HotSpot(TM) 64-Bit Server VM, 11.0.2+9-LTS
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
Benchmark results
Benchmark Mode Cnt Score Error Units
CompressBenchmark.testFieldEnum avgt 5 1861,603 ± 632,653 ns/op
CompressBenchmark.testSwitchEnum avgt 5 10149,055 ± 338,581 ns/op
Memory allocations
Each benchmark was run separately ensuring the other enum class wasn't loaded. The memory usage was analyzed with YourKit.
BooleanFieldEnum
non-heap memory usage:
G1 Eden space was 13 MB
.
SwitchEnum
non-heap memory usage:
G1 Eden space was 12 MB
.
Conclusions
BooleanFieldEnum
is roughly 5
times faster than SwitchEnum
while using pretty much the same amount of memory.
The main worry I had with the switch
approach is that the constant lookup table could waste more memory than all the boolean
fields. It turns out this is false. Additionally, a table lookup is far more expensive than a local field access.