Also see https://github.com/openjdk/jdk/pull/15614, which removes caching in `AbstractMap` etc, meaning once Valhalla is out, the anonymous set will be a value object with no overhead. In addition, hotspot already has an escape analysis mechanism which can optimize iterators to index for loops if it determines an iterator does not get shared.
On Fri, Feb 2, 2024 at 2:54 PM Jason Mehrens <jason_mehr...@hotmail.com> wrote: > See: https://bugs.openjdk.org/browse/JDK-8193128 > > Jason > ------------------------------ > *From:* core-libs-dev <core-libs-dev-r...@openjdk.org> on behalf of Ryan > Ernst <r...@iernst.net> > *Sent:* Friday, February 2, 2024 1:42 PM > *To:* core-libs-dev@openjdk.org <core-libs-dev@openjdk.org> > *Subject:* Object creation from iterating Map.of()/Set.of()/List.of() > > 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. >