Skip to content

perf: skip builder allocation for empty source in HashMap.from#26280

Open
He-Pin wants to merge 1 commit into
scala:mainfrom
He-Pin:perf/hashmap-from-empty
Open

perf: skip builder allocation for empty source in HashMap.from#26280
He-Pin wants to merge 1 commit into
scala:mainfrom
He-Pin:perf/hashmap-from-empty

Conversation

@He-Pin

@He-Pin He-Pin commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Description

Skip builder allocation for empty source in HashMap.from.

Problem

HashMap.from did not check source.knownSize == 0 before allocating a builder, unlike HashSet.from which has this optimization. For empty sources, this unnecessarily allocates a HashMapBuilder, calls ensureUnaliased, and then returns HashMap.empty.

Solution

Add case _ if source.knownSize == 0 => empty[K, V] to HashMap.from, matching the pattern in HashSet.from.

Result

HashMap.from now returns the singleton empty map directly for empty sources, avoiding unnecessary builder allocation.

LLM Policy

LLM-based tools were used extensively in this contribution. The code was reviewed and tested locally before submission.

Motivation:
HashMap.from did not check source.knownSize == 0 before allocating
a builder, unlike HashSet.from which has this optimization. For
empty sources, this unnecessarily allocates a HashMapBuilder, calls
ensureUnaliased, and then returns HashMap.empty.

Modification:
Add case _ if source.knownSize == 0 => empty[K, V] to HashMap.from,
matching the pattern in HashSet.from.

Result:
HashMap.from now returns the singleton empty map directly for empty
sources, avoiding unnecessary builder allocation.
@He-Pin He-Pin marked this pull request as ready for review June 8, 2026 17:19
@He-Pin He-Pin requested a review from a team as a code owner June 8, 2026 17:19

@SolalPirelli SolalPirelli left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that this matches HashSet better I think we should take it https://github.com/scala/scala3/blob/main/library/src/scala/collection/immutable/HashSet.scala#L1963

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants