Object creation from iterating Map.of()/Set.of()/List.of()
Ryan Ernst
ryan at iernst.net
Fri Feb 2 19:42:45 UTC 2024
The newer “of” methods in collections are really nice, they make creating these collections much easier and often result in better performance.
However, the empty collection cases with Map.of()/Set.of()/List.of() has one small downside. The implementations within ImmutableCollections use non-specialized implementations for zero sized collections. For example, ImmutableCollections.EMPTY_MAP is a MapN. If you iterate over that Map, even if it is empty as in the case for Map.of(), a new anonymous AbstractSet is created. In comparison, Collections.emptyMap().entrySet() returns emptySet().
I don’t know what the reasoning was for rebuilding the empty based variants in ImmutableCollections. But regardless, it seems like the empty collections defined in ImmutableCollections should likewise never construct any objects.
I’m happy to raise a PR to either mimic or reuse the empty collection implementations from Collections, but I wanted to check there isn’t some reasoning the of() methods work this way.
More information about the core-libs-dev
mailing list