RFR: 8299444 java.util.Set.copyOf allocates needlessly for empty input collections

Aleksey Shipilev shade at openjdk.org
Wed Jan 4 16:25:50 UTC 2023


On Wed, 4 Jan 2023 14:41:20 GMT, Viktor Klang <duke at openjdk.org> wrote:

> Currently Set.copyOf allocates both a HashSet and a new empty array when the input collection is empty.
> 
> This patch avoids allocating anything for the case where the parameter collection's isEmpty returns true.

Looks okay. This relies a bit on `isEmpty()` to be actually fast, but it seems unlikely it would be worse than doing the `toArray()`.

`Map.copyOf` has the same opportunity.

-------------

Marked as reviewed by shade (Reviewer).

PR: https://git.openjdk.org/jdk/pull/11847


More information about the core-libs-dev mailing list