Daniel Karnaukh
01/22/2024, 10:10 PM(mutable)setOf
using reified genericsto account for enum sets, which are faster than your average HashSet
for enums. However, (mutable)setOf
stipulates that the returned set maintains insertion order, so I quickly wrote up a LinkedEnumSet
and benchmarked it:
BenchEnum.addEnum avgt 25 1.643 ± 0.135 ns/op
BenchEnum.addEnumSet avgt 25 1.475 ± 0.050 ns/op
BenchEnum.addMutableSet avgt 25 10.844 ± 0.687 ns/op
BenchEnum.containsEnum avgt 25 1.354 ± 0.015 ns/op
BenchEnum.containsEnumSet avgt 25 1.260 ± 0.044 ns/op
BenchEnum.containsMutableSet avgt 25 2.800 ± 0.348 ns/op
BenchEnum.iterateEnum avgt 25 27.879 ± 0.350 ns/op
BenchEnum.iterateEnumSet avgt 25 10.458 ± 0.105 ns/op
BenchEnum.iterateMutableSet avgt 25 9.721 ± 0.097 ns/op
BenchEnum.removeEnum avgt 25 1.573 ± 0.140 ns/op
BenchEnum.removeEnumSet avgt 25 1.442 ± 0.091 ns/op
BenchEnum.removeMutableSet avgt 25 3.367 ± 0.803 ns/op
In here, *Enum
is the LinkedEnumSet
, *EnumSet
is the java.util.EnumSet
, and *MutableSet
is the set returned by toMutableSet
. As you can see, LinkedEnumSet
is significantly faster than MutableSet
except in the case of iteration, which I have no idea why. Does my idea to specialize (mutable)setOf
(and the (mutable)mapOf
possibly too) have any merit? Benchmark source can be found here.