Question

Usually people say we should use EnumMap when the key is an enum. But what about this case I want to count the frequencies of each enum value, it seems like trove4j TObjectIntHashMap is better in code.

The following is the example with trove4j collection:

TObjectIntMap<ExtraOperator> extraOpr = new TObjectIntHashMap<ExtraOperator>();
extraOpr.adjustOrPutValue(ExtraOperator.ternary, 1, 1);

In case of EnumMap, the code looks like:

Map<ExtraOperator, Integer> extraOpr = Maps.newEnumMap(ExtraOperator.class);
if (extraOpr.containsKey(ExtraOperator.ternary)) {
    extraOpr.put(ExtraOperator.ternary, extraOpr.get(ExtraOperator.ternary) + 1);
} else {
    extraOpr.put(ExtraOperator.ternary, 1);
}

So, trove4j checks existence internally and can auto-increment the value, which makes the code more concise. EnumMap use enum as key has higher performance but the retrieval and increment of the Integer(boxing and unboxing) also cost time.

Which one would be better if we consider low memory cost and fast speed?

Was it helpful?

Solution

If you want lower cost/faster you could use a plain array.

 static final ExtraOperator[] VALUES = ExtraOperator.values();

 private final int[] counts = new int[VALUES.length];

 // to count.
 counts[e.ordinal()]++;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top