2

While exploring Java EnumSet, i cam across two package-private class,

  1. RegularEnumSet
  2. JumboEnumSet

From EnumSet source :

if (universe.length <= 64)
   return new RegularEnumSet<>(elementType, universe);
else
   return new JumboEnumSet<>(elementType, universe);

Also RegularEnumSet Constructor look like :

RegularEnumSet(Class<E>elementType, Enum[] universe) {
    super(elementType, universe);
}

whereas in case of JumboEnumSet constructor is :

JumboEnumSet(Class<E>elementType, Enum[] universe) {
   super(elementType, universe);
   elements = new long[(universe.length + 63) >>> 6];
}

So my doubts are :

  • Why it uses different EnumSet depending on size.How it impacts performance?

  • What is the logic behind JumboEnumSet of using elements array?

Prateek
  • 12,014
  • 12
  • 60
  • 81

1 Answers1

7
  • RegularEnumSet uses a single long as its bit-array, so it only holds 64 bits, so it can only keep track of the presence or absence of up to 64 enum values.
  • JumboEnumSet uses a long[], so it can hold arbitrarily many bits, so it can keep track of the presence or absence of arbitrarily many enum values.

RegularEnumSet has slightly better performance, because it has a little less indirection (it stores all its data inside the object, instead of having to go retrieve a separate array to find its data), a little less bit manipulation (it doesn't have to find the array index), etc. (I don't know how significant these things are in practice, but I'm sure that they wouldn't have implemented this approach if it weren't justified.)

ruakh
  • 175,680
  • 26
  • 273
  • 307