Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimization done by an EnumMap/EnumSet

I recently read an article about EnumMap. It's written that "using EnumMap brings implementation specific benefits which is done for enum keys, In short EnumMap is optimized Map implementation exclusively for enum keys."

It's also written that "Enum is implemented using Arrays and common operations result in constant time. So if you are thinking of an high performance Map, EnumMap could be decent choice for enumeration data."


Can someone point me out how this optimizations are done ? ("operations result in constant time")
like image 632
user2336315 Avatar asked May 19 '13 17:05

user2336315


2 Answers

Looking at the documentation for EnumMap:

A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

Enum maps are maintained in the natural order of their keys (the order in which the enum constants are declared). This is reflected in the iterators returned by the collections views (keySet(), entrySet(), and values()).

In short, an EnumMap is just an array, of the type of the values of the map. In other words, an EnumMap<SomeEnum, SomeValue>, would be just a SomeValue[].

How are the indexes assigned, you might ask? They are assigned by the natural order of the enum. Example:

enum Day {
    MON, TUE, WED, THU, FRI, SAT, SUN
}

The above enum has the following natural order.

MON TUE WED THU FRI SAT SUN
 0   1   2   3   4   5   6

So, an operation like map.put(Day.FRI, "Yay!") can actually be viewed as:

array[4] = "Yay!";

Array access is a constant time operation, and that's why the EnumMap benefits of it as well. The look up (get()) works just the same way.

like image 112
afsantos Avatar answered Nov 15 '22 03:11

afsantos


As you can see from the source, an EnumMap contains an array of objects of length exactly the number of values in the enum. For (for instance) put and get, the ordinal value of the enum value is used as array index. This operation obviously takes constant time.

like image 33
Vincent van der Weele Avatar answered Nov 15 '22 03:11

Vincent van der Weele