Use nearest prime sizing for collection trimming - #132098

Merged
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing
Aug 31, 2026
Merged

Use nearest prime sizing for collection trimming#132098
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing

Conversation

@tannergooding

@tannergoodingtannergooding commented Aug 10, 2026

Copy link
Copy Markdown
Member

Dictionary<TKey, TValue> and HashSet<T> currently use the growth-oriented cached prime table for TrimExcess, which can retain nearly 20% more storage than requested. Select the nearest valid prime for compaction while preserving the existing cached-prime behavior for construction, EnsureCapacity, and automatic growth.

The shared prime-selection implementation now lives under libraries/Common rather than being duplicated by MetadataLoadContext.

Internal prime search

These are microbenchmarks of the computed-prime fallback beyond the precomputed cache. They measure the helper directly, not end-user TrimExcess performance. Visiting only 6k +/- 1 candidates and reusing the square-root limit improved representative searches by 33-36% locally:

MinimumBeforeAfter
1,00067.51 ns43.22 ns
5,001,2342.185 us1.458 us
1,000,000,00030.04 us19.85 us

TrimExcess

To isolate destination sizing from other implementation differences, these benchmarks use the PR implementation for both cases and compact to either the previous cached-prime target or the new nearest-prime target. Copy throughput is mixed within a few percent while allocation falls with the retained capacity:

CollectionCountCached targetNearest targetTime ratioAllocated beforeAllocated after
Dictionary<int, int>100,000108,631100,0031.02x2.07 MB1.91 MB
Dictionary<int, int>1,000,0001,162,6871,000,0031.03x22.18 MB19.07 MB
Dictionary<int, int>5,001,2345,999,4715,001,2510.98x114.43 MB95.39 MB
HashSet<int>100,000108,631100,0031.06x1.66 MB1.53 MB
HashSet<int>1,000,0001,162,6871,000,0030.98x17.74 MB15.26 MB
HashSet<int>5,001,2345,999,4715,001,2510.99x91.54 MB76.31 MB

At 5,001,234 entries, this avoids 998,220 slots -- approximately 19.04 MiB for Dictionary<int, int> or 15.23 MiB for HashSet<int> across the bucket and entry arrays.

Addresses the TrimExcess sizing problem discussed in #132051.

Note

This pull request description was drafted with GitHub Copilot.

tannergoodingand others added 2 commits August 10, 2026 13:36
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI lite review requested due to automatic review settings August 10, 2026 20:57
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

CopilotAI 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.

Pull request overview

Updates internal hash-table sizing helpers so Dictionary<TKey, TValue>.TrimExcess(int) and HashSet<T>.TrimExcess(int) choose a tighter “nearest valid prime” capacity (rather than the growth-oriented cached prime table), reducing retained storage after trimming while keeping the existing cached-prime behavior for construction/growth paths.

Changes:

  • Added a new prime-sizing path (GetPrimeAtLeast) and optimized prime search in System.Collections.HashHelpers.
  • Switched Dictionary/HashSetTrimExcess(int) to use the tighter prime sizing and refactored trim rehashing into compacting resize helpers.
  • Added regression tests asserting the new TrimExcess capacity selection behavior.
Show a summary per file
FileDescription
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/HashHelpers.csOptimizes prime selection in MetadataLoadContext’s local HashHelpers.
src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.csAdds GetPrimeAtLeast and updates prime-testing/search logic used by core collections.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.csUses tighter prime sizing for TrimExcess and introduces compacting resize/copy helpers.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.csUses tighter prime sizing for TrimExcess and introduces compacting resize helper.
src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.csAdds test coverage for the new HashSet.TrimExcess sizing behavior.
src/libraries/System.Collections/tests/Generic/Dictionary/Dictionary.Generic.Tests.csAdds test coverage for the new Dictionary.TrimExcess sizing behavior.

Review details

  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:09

CopilotAI 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.

Review details

  • Files reviewed: 17/17 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:49

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs Outdated
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 04:46

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 05:04
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

CopilotAI 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.

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

CopilotAI review requested due to automatic review settings August 14, 2026 14:37
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from d8ccc7f to 131ba6cCompareAugust 14, 2026 14:38
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from 131ba6c to 609a2f2CompareAugust 14, 2026 14:38

CopilotAI 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.

Review details

Suppressed comments (1)

src/libraries/Common/src/System/Collections/HashHelpers.cs:146

  • GetPrimeAtLeastCore uses an unbounded while (true) and increments candidate without any overflow/termination check. For large min values (e.g., int.MaxValue from public Dictionary.TrimExcess(int) / HashSet.TrimExcess(int)), candidate += increment can overflow to a negative value and the loop will never terminate, potentially hanging the caller.
  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@vojtechgadurek

vojtechgadurek commented Aug 14, 2026

Copy link
Copy Markdown

Hi all, I was just wondering, why we do not make the prime array denser? If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

The performance hit for searching the correct prime should be neglible to the overall cost of copy of all elements (if using linear search).

It may be noticable, if someone is allocating large dictionaries and then not using them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

This comes at other cost, including pessimizing the common case of automatic growth in favor of the less common case of explicit user sizing.

There's a lot of primes, with the largest gap being (when accounting for the HashPrime of 101) being roughly 318 between any two primes between [0, int.MaxValue] (there's roughly 465m total primes in that range, not accounting for the hash prime filtering). On the other hand, finding the next largest prime via computation is also not terribly expensive and the more expensive cost is actually allocating+copying, particularly for larger counts (somewhere around 1500x Int128 is where I measured it start to be non-impactful).

It may be noticable, if someone is allocating large dictionaries and then not using them.

Users intentionally over-allocating isn't a concern. That's on them to fix if its problematic.

@tannergooding

tannergooding commented Aug 14, 2026

Copy link
Copy Markdown
MemberAuthor

Unfortunately, there are still major problems with the current version of this PR:

I appreciate the feedback and while I've already addressed many of these statements on the other thread, I'll summarize the general response here as well.

Given effectively random hashes (which is expected for most inputs and is how most GetHashCode implementations are built), any given dictionary follows the standard 1 + ((count / capacity) / 2) algorithm (where count / capacity is effectively the load factor) for the expected average number of lookups required. So when count is approx equal to capacity, you get an expected 1.5 comparisons per lookup. When capacity is roughly double count, then it becomes 1.25; then 1.125 at 4x the count, and so on. You need capacity to be roughly 10x the count to hit 1.05.

The existing lookup table entries averages about a 1.2 growth between prime entries and so the best case scenario when using exclusively the lookup table is around 1.417 average lookups (in contrast to the 1.5 base quoted above). We could have the algorithm always pick capacity * 1.2 but then that is misleading to users and what they request explicitly and so its safer and simpler to just do the "nearest prime" and let them scale it themselves if desired.

Then, while the 1 vs 1.4 vs 1.5 vs ... average lookups follow big-O notation, that isn't necessarily meaningful and there are other aspects to be considered. This includes that at smaller n, you're actually making memory accesses more random and so likely hurting perf because you're less likely to hit the cache. There is also the aspect of GC pressure, cost of allocating, zeroing, and copying that memory, etc. So the real world consideration is very different from just looking at the raw theoretical math.

Using Guid as an example (and noting that other types will have different measurements/costs), we save 4.96 MiB at 1m entries while at 4.2m entries we see 24.4 MiB in allocating savings. The perf for these however ends up being about net neutral with it being 2-4% faster in optimal cases and around 3-6% slower in the worst case scenarios; while distinct runs fluctuate around 5% on average just due to things like loop alignment and memory alignment that you happen to be given by the GC. Showcasing that this isn't likely a meaningful scenario and the winnings are really the size savings with little impact to real world perf for that theoretical 0.08 savings on average lookups done.

This then changes nothing with regards to what users could already see/experience. That is, the perf characteristics here are entirely dependent on the count to capacity ratio. Even with the prime table picking larger than necessary primes, the actual count could end up being a load capacity that is close to 1.0 and therefore could already see that 1.5 average. If a user actually cared, they'd need to use FrozenDictionary (to try and get 1.05x-1.25x, which is its target range based on count) or to explicitly specify a larger capacity; in which case this PR improves their ability to optimize for their scenario as it gives them what they ask for.


There are few things that are true wins or true losses, most are balanced based on many factors.

This PR in particular has one easy win in improving the prime lookup perf, at the cost of more code and algorithmic complexity.

It then has a different win in allowing TrimExcess to respect the user specified size (rather than choosing something that is in up to 1.2x larger), but at the cost of meaning users explicitly sizing their dictionaries need to better ensure they're picking an appropriate size -- which again is something they already had to consider for many specified capacities, just not all of them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

This is also notably not something for .NET 11, it'd be for .NET 12; and so it's something we have essentially a full 15 months to get feedback around and to tune if needed, including if we simply want to always choose capacity * 1.2x to maintain the existing lookup table distancing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 28, 2026 15:26

CopilotAI 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.

Copilot review overview

Review tier: Lite
Findings: None

@tannergooding

Copy link
Copy Markdown
MemberAuthor

Resolved merge conflicts. @MihaZupan, @eiriktsarpalis could this get re-review.

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
@tannergooding

Copy link
Copy Markdown
MemberAuthor

/ba-g unrelated crypto test failures

@tannergooding
tannergooding merged commit 98a0a46 into dotnet:mainAug 31, 2026
130 of 134 checks passed
@tannergooding
tannergooding deleted the tannergooding-dictionary-prime-sizing branch August 31, 2026 14:56
@dotnet-milestone-botdotnet-milestone-botBot added this to the 12.0-preview1 milestone Aug 31, 2026
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants

@tannergooding@verelpode@vojtechgadurek@eiriktsarpalis@jkotas@PranavSenthilnathan@MihaZupan@hamarb123@rzikm
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Use nearest prime sizing for collection trimming - #132098

Merged
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing
Aug 31, 2026
Merged

Use nearest prime sizing for collection trimming#132098
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing

Conversation

@tannergooding

@tannergoodingtannergooding commented Aug 10, 2026

Copy link
Copy Markdown
Member

Dictionary<TKey, TValue> and HashSet<T> currently use the growth-oriented cached prime table for TrimExcess, which can retain nearly 20% more storage than requested. Select the nearest valid prime for compaction while preserving the existing cached-prime behavior for construction, EnsureCapacity, and automatic growth.

The shared prime-selection implementation now lives under libraries/Common rather than being duplicated by MetadataLoadContext.

Internal prime search

These are microbenchmarks of the computed-prime fallback beyond the precomputed cache. They measure the helper directly, not end-user TrimExcess performance. Visiting only 6k +/- 1 candidates and reusing the square-root limit improved representative searches by 33-36% locally:

MinimumBeforeAfter
1,00067.51 ns43.22 ns
5,001,2342.185 us1.458 us
1,000,000,00030.04 us19.85 us

TrimExcess

To isolate destination sizing from other implementation differences, these benchmarks use the PR implementation for both cases and compact to either the previous cached-prime target or the new nearest-prime target. Copy throughput is mixed within a few percent while allocation falls with the retained capacity:

CollectionCountCached targetNearest targetTime ratioAllocated beforeAllocated after
Dictionary<int, int>100,000108,631100,0031.02x2.07 MB1.91 MB
Dictionary<int, int>1,000,0001,162,6871,000,0031.03x22.18 MB19.07 MB
Dictionary<int, int>5,001,2345,999,4715,001,2510.98x114.43 MB95.39 MB
HashSet<int>100,000108,631100,0031.06x1.66 MB1.53 MB
HashSet<int>1,000,0001,162,6871,000,0030.98x17.74 MB15.26 MB
HashSet<int>5,001,2345,999,4715,001,2510.99x91.54 MB76.31 MB

At 5,001,234 entries, this avoids 998,220 slots -- approximately 19.04 MiB for Dictionary<int, int> or 15.23 MiB for HashSet<int> across the bucket and entry arrays.

Addresses the TrimExcess sizing problem discussed in #132051.

Note

This pull request description was drafted with GitHub Copilot.

tannergoodingand others added 2 commits August 10, 2026 13:36
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI lite review requested due to automatic review settings August 10, 2026 20:57
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

CopilotAI 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.

Pull request overview

Updates internal hash-table sizing helpers so Dictionary<TKey, TValue>.TrimExcess(int) and HashSet<T>.TrimExcess(int) choose a tighter “nearest valid prime” capacity (rather than the growth-oriented cached prime table), reducing retained storage after trimming while keeping the existing cached-prime behavior for construction/growth paths.

Changes:

  • Added a new prime-sizing path (GetPrimeAtLeast) and optimized prime search in System.Collections.HashHelpers.
  • Switched Dictionary/HashSetTrimExcess(int) to use the tighter prime sizing and refactored trim rehashing into compacting resize helpers.
  • Added regression tests asserting the new TrimExcess capacity selection behavior.
Show a summary per file
FileDescription
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/HashHelpers.csOptimizes prime selection in MetadataLoadContext’s local HashHelpers.
src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.csAdds GetPrimeAtLeast and updates prime-testing/search logic used by core collections.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.csUses tighter prime sizing for TrimExcess and introduces compacting resize/copy helpers.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.csUses tighter prime sizing for TrimExcess and introduces compacting resize helper.
src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.csAdds test coverage for the new HashSet.TrimExcess sizing behavior.
src/libraries/System.Collections/tests/Generic/Dictionary/Dictionary.Generic.Tests.csAdds test coverage for the new Dictionary.TrimExcess sizing behavior.

Review details

  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:09

CopilotAI 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.

Review details

  • Files reviewed: 17/17 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:49

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs Outdated
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 04:46

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 05:04
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

CopilotAI 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.

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

CopilotAI review requested due to automatic review settings August 14, 2026 14:37
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from d8ccc7f to 131ba6cCompareAugust 14, 2026 14:38
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from 131ba6c to 609a2f2CompareAugust 14, 2026 14:38

CopilotAI 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.

Review details

Suppressed comments (1)

src/libraries/Common/src/System/Collections/HashHelpers.cs:146

  • GetPrimeAtLeastCore uses an unbounded while (true) and increments candidate without any overflow/termination check. For large min values (e.g., int.MaxValue from public Dictionary.TrimExcess(int) / HashSet.TrimExcess(int)), candidate += increment can overflow to a negative value and the loop will never terminate, potentially hanging the caller.
  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@vojtechgadurek

vojtechgadurek commented Aug 14, 2026

Copy link
Copy Markdown

Hi all, I was just wondering, why we do not make the prime array denser? If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

The performance hit for searching the correct prime should be neglible to the overall cost of copy of all elements (if using linear search).

It may be noticable, if someone is allocating large dictionaries and then not using them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

This comes at other cost, including pessimizing the common case of automatic growth in favor of the less common case of explicit user sizing.

There's a lot of primes, with the largest gap being (when accounting for the HashPrime of 101) being roughly 318 between any two primes between [0, int.MaxValue] (there's roughly 465m total primes in that range, not accounting for the hash prime filtering). On the other hand, finding the next largest prime via computation is also not terribly expensive and the more expensive cost is actually allocating+copying, particularly for larger counts (somewhere around 1500x Int128 is where I measured it start to be non-impactful).

It may be noticable, if someone is allocating large dictionaries and then not using them.

Users intentionally over-allocating isn't a concern. That's on them to fix if its problematic.

@tannergooding

tannergooding commented Aug 14, 2026

Copy link
Copy Markdown
MemberAuthor

Unfortunately, there are still major problems with the current version of this PR:

I appreciate the feedback and while I've already addressed many of these statements on the other thread, I'll summarize the general response here as well.

Given effectively random hashes (which is expected for most inputs and is how most GetHashCode implementations are built), any given dictionary follows the standard 1 + ((count / capacity) / 2) algorithm (where count / capacity is effectively the load factor) for the expected average number of lookups required. So when count is approx equal to capacity, you get an expected 1.5 comparisons per lookup. When capacity is roughly double count, then it becomes 1.25; then 1.125 at 4x the count, and so on. You need capacity to be roughly 10x the count to hit 1.05.

The existing lookup table entries averages about a 1.2 growth between prime entries and so the best case scenario when using exclusively the lookup table is around 1.417 average lookups (in contrast to the 1.5 base quoted above). We could have the algorithm always pick capacity * 1.2 but then that is misleading to users and what they request explicitly and so its safer and simpler to just do the "nearest prime" and let them scale it themselves if desired.

Then, while the 1 vs 1.4 vs 1.5 vs ... average lookups follow big-O notation, that isn't necessarily meaningful and there are other aspects to be considered. This includes that at smaller n, you're actually making memory accesses more random and so likely hurting perf because you're less likely to hit the cache. There is also the aspect of GC pressure, cost of allocating, zeroing, and copying that memory, etc. So the real world consideration is very different from just looking at the raw theoretical math.

Using Guid as an example (and noting that other types will have different measurements/costs), we save 4.96 MiB at 1m entries while at 4.2m entries we see 24.4 MiB in allocating savings. The perf for these however ends up being about net neutral with it being 2-4% faster in optimal cases and around 3-6% slower in the worst case scenarios; while distinct runs fluctuate around 5% on average just due to things like loop alignment and memory alignment that you happen to be given by the GC. Showcasing that this isn't likely a meaningful scenario and the winnings are really the size savings with little impact to real world perf for that theoretical 0.08 savings on average lookups done.

This then changes nothing with regards to what users could already see/experience. That is, the perf characteristics here are entirely dependent on the count to capacity ratio. Even with the prime table picking larger than necessary primes, the actual count could end up being a load capacity that is close to 1.0 and therefore could already see that 1.5 average. If a user actually cared, they'd need to use FrozenDictionary (to try and get 1.05x-1.25x, which is its target range based on count) or to explicitly specify a larger capacity; in which case this PR improves their ability to optimize for their scenario as it gives them what they ask for.


There are few things that are true wins or true losses, most are balanced based on many factors.

This PR in particular has one easy win in improving the prime lookup perf, at the cost of more code and algorithmic complexity.

It then has a different win in allowing TrimExcess to respect the user specified size (rather than choosing something that is in up to 1.2x larger), but at the cost of meaning users explicitly sizing their dictionaries need to better ensure they're picking an appropriate size -- which again is something they already had to consider for many specified capacities, just not all of them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

This is also notably not something for .NET 11, it'd be for .NET 12; and so it's something we have essentially a full 15 months to get feedback around and to tune if needed, including if we simply want to always choose capacity * 1.2x to maintain the existing lookup table distancing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 28, 2026 15:26

CopilotAI 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.

Copilot review overview

Review tier: Lite
Findings: None

@tannergooding

Copy link
Copy Markdown
MemberAuthor

Resolved merge conflicts. @MihaZupan, @eiriktsarpalis could this get re-review.

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
@tannergooding

Copy link
Copy Markdown
MemberAuthor

/ba-g unrelated crypto test failures

@tannergooding
tannergooding merged commit 98a0a46 into dotnet:mainAug 31, 2026
130 of 134 checks passed
@tannergooding
tannergooding deleted the tannergooding-dictionary-prime-sizing branch August 31, 2026 14:56
@dotnet-milestone-botdotnet-milestone-botBot added this to the 12.0-preview1 milestone Aug 31, 2026
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants

@tannergooding@verelpode@vojtechgadurek@eiriktsarpalis@jkotas@PranavSenthilnathan@MihaZupan@hamarb123@rzikm
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Use nearest prime sizing for collection trimming - #132098

Merged
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing
Aug 31, 2026
Merged

Use nearest prime sizing for collection trimming#132098
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing

Conversation

@tannergooding

@tannergoodingtannergooding commented Aug 10, 2026

Copy link
Copy Markdown
Member

Dictionary<TKey, TValue> and HashSet<T> currently use the growth-oriented cached prime table for TrimExcess, which can retain nearly 20% more storage than requested. Select the nearest valid prime for compaction while preserving the existing cached-prime behavior for construction, EnsureCapacity, and automatic growth.

The shared prime-selection implementation now lives under libraries/Common rather than being duplicated by MetadataLoadContext.

Internal prime search

These are microbenchmarks of the computed-prime fallback beyond the precomputed cache. They measure the helper directly, not end-user TrimExcess performance. Visiting only 6k +/- 1 candidates and reusing the square-root limit improved representative searches by 33-36% locally:

MinimumBeforeAfter
1,00067.51 ns43.22 ns
5,001,2342.185 us1.458 us
1,000,000,00030.04 us19.85 us

TrimExcess

To isolate destination sizing from other implementation differences, these benchmarks use the PR implementation for both cases and compact to either the previous cached-prime target or the new nearest-prime target. Copy throughput is mixed within a few percent while allocation falls with the retained capacity:

CollectionCountCached targetNearest targetTime ratioAllocated beforeAllocated after
Dictionary<int, int>100,000108,631100,0031.02x2.07 MB1.91 MB
Dictionary<int, int>1,000,0001,162,6871,000,0031.03x22.18 MB19.07 MB
Dictionary<int, int>5,001,2345,999,4715,001,2510.98x114.43 MB95.39 MB
HashSet<int>100,000108,631100,0031.06x1.66 MB1.53 MB
HashSet<int>1,000,0001,162,6871,000,0030.98x17.74 MB15.26 MB
HashSet<int>5,001,2345,999,4715,001,2510.99x91.54 MB76.31 MB

At 5,001,234 entries, this avoids 998,220 slots -- approximately 19.04 MiB for Dictionary<int, int> or 15.23 MiB for HashSet<int> across the bucket and entry arrays.

Addresses the TrimExcess sizing problem discussed in #132051.

Note

This pull request description was drafted with GitHub Copilot.

tannergoodingand others added 2 commits August 10, 2026 13:36
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI lite review requested due to automatic review settings August 10, 2026 20:57
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

CopilotAI 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.

Pull request overview

Updates internal hash-table sizing helpers so Dictionary<TKey, TValue>.TrimExcess(int) and HashSet<T>.TrimExcess(int) choose a tighter “nearest valid prime” capacity (rather than the growth-oriented cached prime table), reducing retained storage after trimming while keeping the existing cached-prime behavior for construction/growth paths.

Changes:

  • Added a new prime-sizing path (GetPrimeAtLeast) and optimized prime search in System.Collections.HashHelpers.
  • Switched Dictionary/HashSetTrimExcess(int) to use the tighter prime sizing and refactored trim rehashing into compacting resize helpers.
  • Added regression tests asserting the new TrimExcess capacity selection behavior.
Show a summary per file
FileDescription
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/HashHelpers.csOptimizes prime selection in MetadataLoadContext’s local HashHelpers.
src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.csAdds GetPrimeAtLeast and updates prime-testing/search logic used by core collections.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.csUses tighter prime sizing for TrimExcess and introduces compacting resize/copy helpers.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.csUses tighter prime sizing for TrimExcess and introduces compacting resize helper.
src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.csAdds test coverage for the new HashSet.TrimExcess sizing behavior.
src/libraries/System.Collections/tests/Generic/Dictionary/Dictionary.Generic.Tests.csAdds test coverage for the new Dictionary.TrimExcess sizing behavior.

Review details

  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:09

CopilotAI 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.

Review details

  • Files reviewed: 17/17 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:49

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs Outdated
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 04:46

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 05:04
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

CopilotAI 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.

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

CopilotAI review requested due to automatic review settings August 14, 2026 14:37
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from d8ccc7f to 131ba6cCompareAugust 14, 2026 14:38
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from 131ba6c to 609a2f2CompareAugust 14, 2026 14:38

CopilotAI 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.

Review details

Suppressed comments (1)

src/libraries/Common/src/System/Collections/HashHelpers.cs:146

  • GetPrimeAtLeastCore uses an unbounded while (true) and increments candidate without any overflow/termination check. For large min values (e.g., int.MaxValue from public Dictionary.TrimExcess(int) / HashSet.TrimExcess(int)), candidate += increment can overflow to a negative value and the loop will never terminate, potentially hanging the caller.
  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@vojtechgadurek

vojtechgadurek commented Aug 14, 2026

Copy link
Copy Markdown

Hi all, I was just wondering, why we do not make the prime array denser? If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

The performance hit for searching the correct prime should be neglible to the overall cost of copy of all elements (if using linear search).

It may be noticable, if someone is allocating large dictionaries and then not using them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

This comes at other cost, including pessimizing the common case of automatic growth in favor of the less common case of explicit user sizing.

There's a lot of primes, with the largest gap being (when accounting for the HashPrime of 101) being roughly 318 between any two primes between [0, int.MaxValue] (there's roughly 465m total primes in that range, not accounting for the hash prime filtering). On the other hand, finding the next largest prime via computation is also not terribly expensive and the more expensive cost is actually allocating+copying, particularly for larger counts (somewhere around 1500x Int128 is where I measured it start to be non-impactful).

It may be noticable, if someone is allocating large dictionaries and then not using them.

Users intentionally over-allocating isn't a concern. That's on them to fix if its problematic.

@tannergooding

tannergooding commented Aug 14, 2026

Copy link
Copy Markdown
MemberAuthor

Unfortunately, there are still major problems with the current version of this PR:

I appreciate the feedback and while I've already addressed many of these statements on the other thread, I'll summarize the general response here as well.

Given effectively random hashes (which is expected for most inputs and is how most GetHashCode implementations are built), any given dictionary follows the standard 1 + ((count / capacity) / 2) algorithm (where count / capacity is effectively the load factor) for the expected average number of lookups required. So when count is approx equal to capacity, you get an expected 1.5 comparisons per lookup. When capacity is roughly double count, then it becomes 1.25; then 1.125 at 4x the count, and so on. You need capacity to be roughly 10x the count to hit 1.05.

The existing lookup table entries averages about a 1.2 growth between prime entries and so the best case scenario when using exclusively the lookup table is around 1.417 average lookups (in contrast to the 1.5 base quoted above). We could have the algorithm always pick capacity * 1.2 but then that is misleading to users and what they request explicitly and so its safer and simpler to just do the "nearest prime" and let them scale it themselves if desired.

Then, while the 1 vs 1.4 vs 1.5 vs ... average lookups follow big-O notation, that isn't necessarily meaningful and there are other aspects to be considered. This includes that at smaller n, you're actually making memory accesses more random and so likely hurting perf because you're less likely to hit the cache. There is also the aspect of GC pressure, cost of allocating, zeroing, and copying that memory, etc. So the real world consideration is very different from just looking at the raw theoretical math.

Using Guid as an example (and noting that other types will have different measurements/costs), we save 4.96 MiB at 1m entries while at 4.2m entries we see 24.4 MiB in allocating savings. The perf for these however ends up being about net neutral with it being 2-4% faster in optimal cases and around 3-6% slower in the worst case scenarios; while distinct runs fluctuate around 5% on average just due to things like loop alignment and memory alignment that you happen to be given by the GC. Showcasing that this isn't likely a meaningful scenario and the winnings are really the size savings with little impact to real world perf for that theoretical 0.08 savings on average lookups done.

This then changes nothing with regards to what users could already see/experience. That is, the perf characteristics here are entirely dependent on the count to capacity ratio. Even with the prime table picking larger than necessary primes, the actual count could end up being a load capacity that is close to 1.0 and therefore could already see that 1.5 average. If a user actually cared, they'd need to use FrozenDictionary (to try and get 1.05x-1.25x, which is its target range based on count) or to explicitly specify a larger capacity; in which case this PR improves their ability to optimize for their scenario as it gives them what they ask for.


There are few things that are true wins or true losses, most are balanced based on many factors.

This PR in particular has one easy win in improving the prime lookup perf, at the cost of more code and algorithmic complexity.

It then has a different win in allowing TrimExcess to respect the user specified size (rather than choosing something that is in up to 1.2x larger), but at the cost of meaning users explicitly sizing their dictionaries need to better ensure they're picking an appropriate size -- which again is something they already had to consider for many specified capacities, just not all of them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

This is also notably not something for .NET 11, it'd be for .NET 12; and so it's something we have essentially a full 15 months to get feedback around and to tune if needed, including if we simply want to always choose capacity * 1.2x to maintain the existing lookup table distancing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 28, 2026 15:26

CopilotAI 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.

Copilot review overview

Review tier: Lite
Findings: None

@tannergooding

Copy link
Copy Markdown
MemberAuthor

Resolved merge conflicts. @MihaZupan, @eiriktsarpalis could this get re-review.

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
@tannergooding

Copy link
Copy Markdown
MemberAuthor

/ba-g unrelated crypto test failures

@tannergooding
tannergooding merged commit 98a0a46 into dotnet:mainAug 31, 2026
130 of 134 checks passed
@tannergooding
tannergooding deleted the tannergooding-dictionary-prime-sizing branch August 31, 2026 14:56
@dotnet-milestone-botdotnet-milestone-botBot added this to the 12.0-preview1 milestone Aug 31, 2026
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants

@tannergooding@verelpode@vojtechgadurek@eiriktsarpalis@jkotas@PranavSenthilnathan@MihaZupan@hamarb123@rzikm
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Use nearest prime sizing for collection trimming - #132098

Merged
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing
Aug 31, 2026
Merged

Use nearest prime sizing for collection trimming#132098
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing

Conversation

@tannergooding

@tannergoodingtannergooding commented Aug 10, 2026

Copy link
Copy Markdown
Member

Dictionary<TKey, TValue> and HashSet<T> currently use the growth-oriented cached prime table for TrimExcess, which can retain nearly 20% more storage than requested. Select the nearest valid prime for compaction while preserving the existing cached-prime behavior for construction, EnsureCapacity, and automatic growth.

The shared prime-selection implementation now lives under libraries/Common rather than being duplicated by MetadataLoadContext.

Internal prime search

These are microbenchmarks of the computed-prime fallback beyond the precomputed cache. They measure the helper directly, not end-user TrimExcess performance. Visiting only 6k +/- 1 candidates and reusing the square-root limit improved representative searches by 33-36% locally:

MinimumBeforeAfter
1,00067.51 ns43.22 ns
5,001,2342.185 us1.458 us
1,000,000,00030.04 us19.85 us

TrimExcess

To isolate destination sizing from other implementation differences, these benchmarks use the PR implementation for both cases and compact to either the previous cached-prime target or the new nearest-prime target. Copy throughput is mixed within a few percent while allocation falls with the retained capacity:

CollectionCountCached targetNearest targetTime ratioAllocated beforeAllocated after
Dictionary<int, int>100,000108,631100,0031.02x2.07 MB1.91 MB
Dictionary<int, int>1,000,0001,162,6871,000,0031.03x22.18 MB19.07 MB
Dictionary<int, int>5,001,2345,999,4715,001,2510.98x114.43 MB95.39 MB
HashSet<int>100,000108,631100,0031.06x1.66 MB1.53 MB
HashSet<int>1,000,0001,162,6871,000,0030.98x17.74 MB15.26 MB
HashSet<int>5,001,2345,999,4715,001,2510.99x91.54 MB76.31 MB

At 5,001,234 entries, this avoids 998,220 slots -- approximately 19.04 MiB for Dictionary<int, int> or 15.23 MiB for HashSet<int> across the bucket and entry arrays.

Addresses the TrimExcess sizing problem discussed in #132051.

Note

This pull request description was drafted with GitHub Copilot.

tannergoodingand others added 2 commits August 10, 2026 13:36
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI lite review requested due to automatic review settings August 10, 2026 20:57
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

CopilotAI 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.

Pull request overview

Updates internal hash-table sizing helpers so Dictionary<TKey, TValue>.TrimExcess(int) and HashSet<T>.TrimExcess(int) choose a tighter “nearest valid prime” capacity (rather than the growth-oriented cached prime table), reducing retained storage after trimming while keeping the existing cached-prime behavior for construction/growth paths.

Changes:

  • Added a new prime-sizing path (GetPrimeAtLeast) and optimized prime search in System.Collections.HashHelpers.
  • Switched Dictionary/HashSetTrimExcess(int) to use the tighter prime sizing and refactored trim rehashing into compacting resize helpers.
  • Added regression tests asserting the new TrimExcess capacity selection behavior.
Show a summary per file
FileDescription
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/HashHelpers.csOptimizes prime selection in MetadataLoadContext’s local HashHelpers.
src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.csAdds GetPrimeAtLeast and updates prime-testing/search logic used by core collections.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.csUses tighter prime sizing for TrimExcess and introduces compacting resize/copy helpers.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.csUses tighter prime sizing for TrimExcess and introduces compacting resize helper.
src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.csAdds test coverage for the new HashSet.TrimExcess sizing behavior.
src/libraries/System.Collections/tests/Generic/Dictionary/Dictionary.Generic.Tests.csAdds test coverage for the new Dictionary.TrimExcess sizing behavior.

Review details

  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:09

CopilotAI 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.

Review details

  • Files reviewed: 17/17 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:49

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs Outdated
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 04:46

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 05:04
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

CopilotAI 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.

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

CopilotAI review requested due to automatic review settings August 14, 2026 14:37
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from d8ccc7f to 131ba6cCompareAugust 14, 2026 14:38
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from 131ba6c to 609a2f2CompareAugust 14, 2026 14:38

CopilotAI 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.

Review details

Suppressed comments (1)

src/libraries/Common/src/System/Collections/HashHelpers.cs:146

  • GetPrimeAtLeastCore uses an unbounded while (true) and increments candidate without any overflow/termination check. For large min values (e.g., int.MaxValue from public Dictionary.TrimExcess(int) / HashSet.TrimExcess(int)), candidate += increment can overflow to a negative value and the loop will never terminate, potentially hanging the caller.
  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@vojtechgadurek

vojtechgadurek commented Aug 14, 2026

Copy link
Copy Markdown

Hi all, I was just wondering, why we do not make the prime array denser? If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

The performance hit for searching the correct prime should be neglible to the overall cost of copy of all elements (if using linear search).

It may be noticable, if someone is allocating large dictionaries and then not using them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

This comes at other cost, including pessimizing the common case of automatic growth in favor of the less common case of explicit user sizing.

There's a lot of primes, with the largest gap being (when accounting for the HashPrime of 101) being roughly 318 between any two primes between [0, int.MaxValue] (there's roughly 465m total primes in that range, not accounting for the hash prime filtering). On the other hand, finding the next largest prime via computation is also not terribly expensive and the more expensive cost is actually allocating+copying, particularly for larger counts (somewhere around 1500x Int128 is where I measured it start to be non-impactful).

It may be noticable, if someone is allocating large dictionaries and then not using them.

Users intentionally over-allocating isn't a concern. That's on them to fix if its problematic.

@tannergooding

tannergooding commented Aug 14, 2026

Copy link
Copy Markdown
MemberAuthor

Unfortunately, there are still major problems with the current version of this PR:

I appreciate the feedback and while I've already addressed many of these statements on the other thread, I'll summarize the general response here as well.

Given effectively random hashes (which is expected for most inputs and is how most GetHashCode implementations are built), any given dictionary follows the standard 1 + ((count / capacity) / 2) algorithm (where count / capacity is effectively the load factor) for the expected average number of lookups required. So when count is approx equal to capacity, you get an expected 1.5 comparisons per lookup. When capacity is roughly double count, then it becomes 1.25; then 1.125 at 4x the count, and so on. You need capacity to be roughly 10x the count to hit 1.05.

The existing lookup table entries averages about a 1.2 growth between prime entries and so the best case scenario when using exclusively the lookup table is around 1.417 average lookups (in contrast to the 1.5 base quoted above). We could have the algorithm always pick capacity * 1.2 but then that is misleading to users and what they request explicitly and so its safer and simpler to just do the "nearest prime" and let them scale it themselves if desired.

Then, while the 1 vs 1.4 vs 1.5 vs ... average lookups follow big-O notation, that isn't necessarily meaningful and there are other aspects to be considered. This includes that at smaller n, you're actually making memory accesses more random and so likely hurting perf because you're less likely to hit the cache. There is also the aspect of GC pressure, cost of allocating, zeroing, and copying that memory, etc. So the real world consideration is very different from just looking at the raw theoretical math.

Using Guid as an example (and noting that other types will have different measurements/costs), we save 4.96 MiB at 1m entries while at 4.2m entries we see 24.4 MiB in allocating savings. The perf for these however ends up being about net neutral with it being 2-4% faster in optimal cases and around 3-6% slower in the worst case scenarios; while distinct runs fluctuate around 5% on average just due to things like loop alignment and memory alignment that you happen to be given by the GC. Showcasing that this isn't likely a meaningful scenario and the winnings are really the size savings with little impact to real world perf for that theoretical 0.08 savings on average lookups done.

This then changes nothing with regards to what users could already see/experience. That is, the perf characteristics here are entirely dependent on the count to capacity ratio. Even with the prime table picking larger than necessary primes, the actual count could end up being a load capacity that is close to 1.0 and therefore could already see that 1.5 average. If a user actually cared, they'd need to use FrozenDictionary (to try and get 1.05x-1.25x, which is its target range based on count) or to explicitly specify a larger capacity; in which case this PR improves their ability to optimize for their scenario as it gives them what they ask for.


There are few things that are true wins or true losses, most are balanced based on many factors.

This PR in particular has one easy win in improving the prime lookup perf, at the cost of more code and algorithmic complexity.

It then has a different win in allowing TrimExcess to respect the user specified size (rather than choosing something that is in up to 1.2x larger), but at the cost of meaning users explicitly sizing their dictionaries need to better ensure they're picking an appropriate size -- which again is something they already had to consider for many specified capacities, just not all of them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

This is also notably not something for .NET 11, it'd be for .NET 12; and so it's something we have essentially a full 15 months to get feedback around and to tune if needed, including if we simply want to always choose capacity * 1.2x to maintain the existing lookup table distancing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 28, 2026 15:26

CopilotAI 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.

Copilot review overview

Review tier: Lite
Findings: None

@tannergooding

Copy link
Copy Markdown
MemberAuthor

Resolved merge conflicts. @MihaZupan, @eiriktsarpalis could this get re-review.

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
@tannergooding

Copy link
Copy Markdown
MemberAuthor

/ba-g unrelated crypto test failures

@tannergooding
tannergooding merged commit 98a0a46 into dotnet:mainAug 31, 2026
130 of 134 checks passed
@tannergooding
tannergooding deleted the tannergooding-dictionary-prime-sizing branch August 31, 2026 14:56
@dotnet-milestone-botdotnet-milestone-botBot added this to the 12.0-preview1 milestone Aug 31, 2026
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants

@tannergooding@verelpode@vojtechgadurek@eiriktsarpalis@jkotas@PranavSenthilnathan@MihaZupan@hamarb123@rzikm
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Use nearest prime sizing for collection trimming - #132098

Merged
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing
Aug 31, 2026
Merged

Use nearest prime sizing for collection trimming#132098
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing

Conversation

@tannergooding

@tannergoodingtannergooding commented Aug 10, 2026

Copy link
Copy Markdown
Member

Dictionary<TKey, TValue> and HashSet<T> currently use the growth-oriented cached prime table for TrimExcess, which can retain nearly 20% more storage than requested. Select the nearest valid prime for compaction while preserving the existing cached-prime behavior for construction, EnsureCapacity, and automatic growth.

The shared prime-selection implementation now lives under libraries/Common rather than being duplicated by MetadataLoadContext.

Internal prime search

These are microbenchmarks of the computed-prime fallback beyond the precomputed cache. They measure the helper directly, not end-user TrimExcess performance. Visiting only 6k +/- 1 candidates and reusing the square-root limit improved representative searches by 33-36% locally:

MinimumBeforeAfter
1,00067.51 ns43.22 ns
5,001,2342.185 us1.458 us
1,000,000,00030.04 us19.85 us

TrimExcess

To isolate destination sizing from other implementation differences, these benchmarks use the PR implementation for both cases and compact to either the previous cached-prime target or the new nearest-prime target. Copy throughput is mixed within a few percent while allocation falls with the retained capacity:

CollectionCountCached targetNearest targetTime ratioAllocated beforeAllocated after
Dictionary<int, int>100,000108,631100,0031.02x2.07 MB1.91 MB
Dictionary<int, int>1,000,0001,162,6871,000,0031.03x22.18 MB19.07 MB
Dictionary<int, int>5,001,2345,999,4715,001,2510.98x114.43 MB95.39 MB
HashSet<int>100,000108,631100,0031.06x1.66 MB1.53 MB
HashSet<int>1,000,0001,162,6871,000,0030.98x17.74 MB15.26 MB
HashSet<int>5,001,2345,999,4715,001,2510.99x91.54 MB76.31 MB

At 5,001,234 entries, this avoids 998,220 slots -- approximately 19.04 MiB for Dictionary<int, int> or 15.23 MiB for HashSet<int> across the bucket and entry arrays.

Addresses the TrimExcess sizing problem discussed in #132051.

Note

This pull request description was drafted with GitHub Copilot.

tannergoodingand others added 2 commits August 10, 2026 13:36
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI lite review requested due to automatic review settings August 10, 2026 20:57
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

CopilotAI 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.

Pull request overview

Updates internal hash-table sizing helpers so Dictionary<TKey, TValue>.TrimExcess(int) and HashSet<T>.TrimExcess(int) choose a tighter “nearest valid prime” capacity (rather than the growth-oriented cached prime table), reducing retained storage after trimming while keeping the existing cached-prime behavior for construction/growth paths.

Changes:

  • Added a new prime-sizing path (GetPrimeAtLeast) and optimized prime search in System.Collections.HashHelpers.
  • Switched Dictionary/HashSetTrimExcess(int) to use the tighter prime sizing and refactored trim rehashing into compacting resize helpers.
  • Added regression tests asserting the new TrimExcess capacity selection behavior.
Show a summary per file
FileDescription
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/HashHelpers.csOptimizes prime selection in MetadataLoadContext’s local HashHelpers.
src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.csAdds GetPrimeAtLeast and updates prime-testing/search logic used by core collections.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.csUses tighter prime sizing for TrimExcess and introduces compacting resize/copy helpers.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.csUses tighter prime sizing for TrimExcess and introduces compacting resize helper.
src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.csAdds test coverage for the new HashSet.TrimExcess sizing behavior.
src/libraries/System.Collections/tests/Generic/Dictionary/Dictionary.Generic.Tests.csAdds test coverage for the new Dictionary.TrimExcess sizing behavior.

Review details

  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:09

CopilotAI 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.

Review details

  • Files reviewed: 17/17 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:49

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs Outdated
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 04:46

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 05:04
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

CopilotAI 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.

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

CopilotAI review requested due to automatic review settings August 14, 2026 14:37
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from d8ccc7f to 131ba6cCompareAugust 14, 2026 14:38
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from 131ba6c to 609a2f2CompareAugust 14, 2026 14:38

CopilotAI 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.

Review details

Suppressed comments (1)

src/libraries/Common/src/System/Collections/HashHelpers.cs:146

  • GetPrimeAtLeastCore uses an unbounded while (true) and increments candidate without any overflow/termination check. For large min values (e.g., int.MaxValue from public Dictionary.TrimExcess(int) / HashSet.TrimExcess(int)), candidate += increment can overflow to a negative value and the loop will never terminate, potentially hanging the caller.
  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@vojtechgadurek

vojtechgadurek commented Aug 14, 2026

Copy link
Copy Markdown

Hi all, I was just wondering, why we do not make the prime array denser? If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

The performance hit for searching the correct prime should be neglible to the overall cost of copy of all elements (if using linear search).

It may be noticable, if someone is allocating large dictionaries and then not using them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

This comes at other cost, including pessimizing the common case of automatic growth in favor of the less common case of explicit user sizing.

There's a lot of primes, with the largest gap being (when accounting for the HashPrime of 101) being roughly 318 between any two primes between [0, int.MaxValue] (there's roughly 465m total primes in that range, not accounting for the hash prime filtering). On the other hand, finding the next largest prime via computation is also not terribly expensive and the more expensive cost is actually allocating+copying, particularly for larger counts (somewhere around 1500x Int128 is where I measured it start to be non-impactful).

It may be noticable, if someone is allocating large dictionaries and then not using them.

Users intentionally over-allocating isn't a concern. That's on them to fix if its problematic.

@tannergooding

tannergooding commented Aug 14, 2026

Copy link
Copy Markdown
MemberAuthor

Unfortunately, there are still major problems with the current version of this PR:

I appreciate the feedback and while I've already addressed many of these statements on the other thread, I'll summarize the general response here as well.

Given effectively random hashes (which is expected for most inputs and is how most GetHashCode implementations are built), any given dictionary follows the standard 1 + ((count / capacity) / 2) algorithm (where count / capacity is effectively the load factor) for the expected average number of lookups required. So when count is approx equal to capacity, you get an expected 1.5 comparisons per lookup. When capacity is roughly double count, then it becomes 1.25; then 1.125 at 4x the count, and so on. You need capacity to be roughly 10x the count to hit 1.05.

The existing lookup table entries averages about a 1.2 growth between prime entries and so the best case scenario when using exclusively the lookup table is around 1.417 average lookups (in contrast to the 1.5 base quoted above). We could have the algorithm always pick capacity * 1.2 but then that is misleading to users and what they request explicitly and so its safer and simpler to just do the "nearest prime" and let them scale it themselves if desired.

Then, while the 1 vs 1.4 vs 1.5 vs ... average lookups follow big-O notation, that isn't necessarily meaningful and there are other aspects to be considered. This includes that at smaller n, you're actually making memory accesses more random and so likely hurting perf because you're less likely to hit the cache. There is also the aspect of GC pressure, cost of allocating, zeroing, and copying that memory, etc. So the real world consideration is very different from just looking at the raw theoretical math.

Using Guid as an example (and noting that other types will have different measurements/costs), we save 4.96 MiB at 1m entries while at 4.2m entries we see 24.4 MiB in allocating savings. The perf for these however ends up being about net neutral with it being 2-4% faster in optimal cases and around 3-6% slower in the worst case scenarios; while distinct runs fluctuate around 5% on average just due to things like loop alignment and memory alignment that you happen to be given by the GC. Showcasing that this isn't likely a meaningful scenario and the winnings are really the size savings with little impact to real world perf for that theoretical 0.08 savings on average lookups done.

This then changes nothing with regards to what users could already see/experience. That is, the perf characteristics here are entirely dependent on the count to capacity ratio. Even with the prime table picking larger than necessary primes, the actual count could end up being a load capacity that is close to 1.0 and therefore could already see that 1.5 average. If a user actually cared, they'd need to use FrozenDictionary (to try and get 1.05x-1.25x, which is its target range based on count) or to explicitly specify a larger capacity; in which case this PR improves their ability to optimize for their scenario as it gives them what they ask for.


There are few things that are true wins or true losses, most are balanced based on many factors.

This PR in particular has one easy win in improving the prime lookup perf, at the cost of more code and algorithmic complexity.

It then has a different win in allowing TrimExcess to respect the user specified size (rather than choosing something that is in up to 1.2x larger), but at the cost of meaning users explicitly sizing their dictionaries need to better ensure they're picking an appropriate size -- which again is something they already had to consider for many specified capacities, just not all of them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

This is also notably not something for .NET 11, it'd be for .NET 12; and so it's something we have essentially a full 15 months to get feedback around and to tune if needed, including if we simply want to always choose capacity * 1.2x to maintain the existing lookup table distancing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 28, 2026 15:26

CopilotAI 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.

Copilot review overview

Review tier: Lite
Findings: None

@tannergooding

Copy link
Copy Markdown
MemberAuthor

Resolved merge conflicts. @MihaZupan, @eiriktsarpalis could this get re-review.

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
@tannergooding

Copy link
Copy Markdown
MemberAuthor

/ba-g unrelated crypto test failures

@tannergooding
tannergooding merged commit 98a0a46 into dotnet:mainAug 31, 2026
130 of 134 checks passed
@tannergooding
tannergooding deleted the tannergooding-dictionary-prime-sizing branch August 31, 2026 14:56
@dotnet-milestone-botdotnet-milestone-botBot added this to the 12.0-preview1 milestone Aug 31, 2026
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants

@tannergooding@verelpode@vojtechgadurek@eiriktsarpalis@jkotas@PranavSenthilnathan@MihaZupan@hamarb123@rzikm
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Use nearest prime sizing for collection trimming - #132098

Merged
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing
Aug 31, 2026
Merged

Use nearest prime sizing for collection trimming#132098
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing

Conversation

@tannergooding

@tannergoodingtannergooding commented Aug 10, 2026

Copy link
Copy Markdown
Member

Dictionary<TKey, TValue> and HashSet<T> currently use the growth-oriented cached prime table for TrimExcess, which can retain nearly 20% more storage than requested. Select the nearest valid prime for compaction while preserving the existing cached-prime behavior for construction, EnsureCapacity, and automatic growth.

The shared prime-selection implementation now lives under libraries/Common rather than being duplicated by MetadataLoadContext.

Internal prime search

These are microbenchmarks of the computed-prime fallback beyond the precomputed cache. They measure the helper directly, not end-user TrimExcess performance. Visiting only 6k +/- 1 candidates and reusing the square-root limit improved representative searches by 33-36% locally:

MinimumBeforeAfter
1,00067.51 ns43.22 ns
5,001,2342.185 us1.458 us
1,000,000,00030.04 us19.85 us

TrimExcess

To isolate destination sizing from other implementation differences, these benchmarks use the PR implementation for both cases and compact to either the previous cached-prime target or the new nearest-prime target. Copy throughput is mixed within a few percent while allocation falls with the retained capacity:

CollectionCountCached targetNearest targetTime ratioAllocated beforeAllocated after
Dictionary<int, int>100,000108,631100,0031.02x2.07 MB1.91 MB
Dictionary<int, int>1,000,0001,162,6871,000,0031.03x22.18 MB19.07 MB
Dictionary<int, int>5,001,2345,999,4715,001,2510.98x114.43 MB95.39 MB
HashSet<int>100,000108,631100,0031.06x1.66 MB1.53 MB
HashSet<int>1,000,0001,162,6871,000,0030.98x17.74 MB15.26 MB
HashSet<int>5,001,2345,999,4715,001,2510.99x91.54 MB76.31 MB

At 5,001,234 entries, this avoids 998,220 slots -- approximately 19.04 MiB for Dictionary<int, int> or 15.23 MiB for HashSet<int> across the bucket and entry arrays.

Addresses the TrimExcess sizing problem discussed in #132051.

Note

This pull request description was drafted with GitHub Copilot.

tannergoodingand others added 2 commits August 10, 2026 13:36
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI lite review requested due to automatic review settings August 10, 2026 20:57
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

CopilotAI 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.

Pull request overview

Updates internal hash-table sizing helpers so Dictionary<TKey, TValue>.TrimExcess(int) and HashSet<T>.TrimExcess(int) choose a tighter “nearest valid prime” capacity (rather than the growth-oriented cached prime table), reducing retained storage after trimming while keeping the existing cached-prime behavior for construction/growth paths.

Changes:

  • Added a new prime-sizing path (GetPrimeAtLeast) and optimized prime search in System.Collections.HashHelpers.
  • Switched Dictionary/HashSetTrimExcess(int) to use the tighter prime sizing and refactored trim rehashing into compacting resize helpers.
  • Added regression tests asserting the new TrimExcess capacity selection behavior.
Show a summary per file
FileDescription
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/HashHelpers.csOptimizes prime selection in MetadataLoadContext’s local HashHelpers.
src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.csAdds GetPrimeAtLeast and updates prime-testing/search logic used by core collections.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.csUses tighter prime sizing for TrimExcess and introduces compacting resize/copy helpers.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.csUses tighter prime sizing for TrimExcess and introduces compacting resize helper.
src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.csAdds test coverage for the new HashSet.TrimExcess sizing behavior.
src/libraries/System.Collections/tests/Generic/Dictionary/Dictionary.Generic.Tests.csAdds test coverage for the new Dictionary.TrimExcess sizing behavior.

Review details

  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:09

CopilotAI 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.

Review details

  • Files reviewed: 17/17 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:49

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs Outdated
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 04:46

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 05:04
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

CopilotAI 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.

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

CopilotAI review requested due to automatic review settings August 14, 2026 14:37
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from d8ccc7f to 131ba6cCompareAugust 14, 2026 14:38
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from 131ba6c to 609a2f2CompareAugust 14, 2026 14:38

CopilotAI 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.

Review details

Suppressed comments (1)

src/libraries/Common/src/System/Collections/HashHelpers.cs:146

  • GetPrimeAtLeastCore uses an unbounded while (true) and increments candidate without any overflow/termination check. For large min values (e.g., int.MaxValue from public Dictionary.TrimExcess(int) / HashSet.TrimExcess(int)), candidate += increment can overflow to a negative value and the loop will never terminate, potentially hanging the caller.
  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@vojtechgadurek

vojtechgadurek commented Aug 14, 2026

Copy link
Copy Markdown

Hi all, I was just wondering, why we do not make the prime array denser? If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

The performance hit for searching the correct prime should be neglible to the overall cost of copy of all elements (if using linear search).

It may be noticable, if someone is allocating large dictionaries and then not using them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

This comes at other cost, including pessimizing the common case of automatic growth in favor of the less common case of explicit user sizing.

There's a lot of primes, with the largest gap being (when accounting for the HashPrime of 101) being roughly 318 between any two primes between [0, int.MaxValue] (there's roughly 465m total primes in that range, not accounting for the hash prime filtering). On the other hand, finding the next largest prime via computation is also not terribly expensive and the more expensive cost is actually allocating+copying, particularly for larger counts (somewhere around 1500x Int128 is where I measured it start to be non-impactful).

It may be noticable, if someone is allocating large dictionaries and then not using them.

Users intentionally over-allocating isn't a concern. That's on them to fix if its problematic.

@tannergooding

tannergooding commented Aug 14, 2026

Copy link
Copy Markdown
MemberAuthor

Unfortunately, there are still major problems with the current version of this PR:

I appreciate the feedback and while I've already addressed many of these statements on the other thread, I'll summarize the general response here as well.

Given effectively random hashes (which is expected for most inputs and is how most GetHashCode implementations are built), any given dictionary follows the standard 1 + ((count / capacity) / 2) algorithm (where count / capacity is effectively the load factor) for the expected average number of lookups required. So when count is approx equal to capacity, you get an expected 1.5 comparisons per lookup. When capacity is roughly double count, then it becomes 1.25; then 1.125 at 4x the count, and so on. You need capacity to be roughly 10x the count to hit 1.05.

The existing lookup table entries averages about a 1.2 growth between prime entries and so the best case scenario when using exclusively the lookup table is around 1.417 average lookups (in contrast to the 1.5 base quoted above). We could have the algorithm always pick capacity * 1.2 but then that is misleading to users and what they request explicitly and so its safer and simpler to just do the "nearest prime" and let them scale it themselves if desired.

Then, while the 1 vs 1.4 vs 1.5 vs ... average lookups follow big-O notation, that isn't necessarily meaningful and there are other aspects to be considered. This includes that at smaller n, you're actually making memory accesses more random and so likely hurting perf because you're less likely to hit the cache. There is also the aspect of GC pressure, cost of allocating, zeroing, and copying that memory, etc. So the real world consideration is very different from just looking at the raw theoretical math.

Using Guid as an example (and noting that other types will have different measurements/costs), we save 4.96 MiB at 1m entries while at 4.2m entries we see 24.4 MiB in allocating savings. The perf for these however ends up being about net neutral with it being 2-4% faster in optimal cases and around 3-6% slower in the worst case scenarios; while distinct runs fluctuate around 5% on average just due to things like loop alignment and memory alignment that you happen to be given by the GC. Showcasing that this isn't likely a meaningful scenario and the winnings are really the size savings with little impact to real world perf for that theoretical 0.08 savings on average lookups done.

This then changes nothing with regards to what users could already see/experience. That is, the perf characteristics here are entirely dependent on the count to capacity ratio. Even with the prime table picking larger than necessary primes, the actual count could end up being a load capacity that is close to 1.0 and therefore could already see that 1.5 average. If a user actually cared, they'd need to use FrozenDictionary (to try and get 1.05x-1.25x, which is its target range based on count) or to explicitly specify a larger capacity; in which case this PR improves their ability to optimize for their scenario as it gives them what they ask for.


There are few things that are true wins or true losses, most are balanced based on many factors.

This PR in particular has one easy win in improving the prime lookup perf, at the cost of more code and algorithmic complexity.

It then has a different win in allowing TrimExcess to respect the user specified size (rather than choosing something that is in up to 1.2x larger), but at the cost of meaning users explicitly sizing their dictionaries need to better ensure they're picking an appropriate size -- which again is something they already had to consider for many specified capacities, just not all of them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

This is also notably not something for .NET 11, it'd be for .NET 12; and so it's something we have essentially a full 15 months to get feedback around and to tune if needed, including if we simply want to always choose capacity * 1.2x to maintain the existing lookup table distancing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 28, 2026 15:26

CopilotAI 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.

Copilot review overview

Review tier: Lite
Findings: None

@tannergooding

Copy link
Copy Markdown
MemberAuthor

Resolved merge conflicts. @MihaZupan, @eiriktsarpalis could this get re-review.

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
@tannergooding

Copy link
Copy Markdown
MemberAuthor

/ba-g unrelated crypto test failures

@tannergooding
tannergooding merged commit 98a0a46 into dotnet:mainAug 31, 2026
130 of 134 checks passed
@tannergooding
tannergooding deleted the tannergooding-dictionary-prime-sizing branch August 31, 2026 14:56
@dotnet-milestone-botdotnet-milestone-botBot added this to the 12.0-preview1 milestone Aug 31, 2026
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants

@tannergooding@verelpode@vojtechgadurek@eiriktsarpalis@jkotas@PranavSenthilnathan@MihaZupan@hamarb123@rzikm
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Use nearest prime sizing for collection trimming - #132098

Merged
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing
Aug 31, 2026
Merged

Use nearest prime sizing for collection trimming#132098
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing

Conversation

@tannergooding

@tannergoodingtannergooding commented Aug 10, 2026

Copy link
Copy Markdown
Member

Dictionary<TKey, TValue> and HashSet<T> currently use the growth-oriented cached prime table for TrimExcess, which can retain nearly 20% more storage than requested. Select the nearest valid prime for compaction while preserving the existing cached-prime behavior for construction, EnsureCapacity, and automatic growth.

The shared prime-selection implementation now lives under libraries/Common rather than being duplicated by MetadataLoadContext.

Internal prime search

These are microbenchmarks of the computed-prime fallback beyond the precomputed cache. They measure the helper directly, not end-user TrimExcess performance. Visiting only 6k +/- 1 candidates and reusing the square-root limit improved representative searches by 33-36% locally:

MinimumBeforeAfter
1,00067.51 ns43.22 ns
5,001,2342.185 us1.458 us
1,000,000,00030.04 us19.85 us

TrimExcess

To isolate destination sizing from other implementation differences, these benchmarks use the PR implementation for both cases and compact to either the previous cached-prime target or the new nearest-prime target. Copy throughput is mixed within a few percent while allocation falls with the retained capacity:

CollectionCountCached targetNearest targetTime ratioAllocated beforeAllocated after
Dictionary<int, int>100,000108,631100,0031.02x2.07 MB1.91 MB
Dictionary<int, int>1,000,0001,162,6871,000,0031.03x22.18 MB19.07 MB
Dictionary<int, int>5,001,2345,999,4715,001,2510.98x114.43 MB95.39 MB
HashSet<int>100,000108,631100,0031.06x1.66 MB1.53 MB
HashSet<int>1,000,0001,162,6871,000,0030.98x17.74 MB15.26 MB
HashSet<int>5,001,2345,999,4715,001,2510.99x91.54 MB76.31 MB

At 5,001,234 entries, this avoids 998,220 slots -- approximately 19.04 MiB for Dictionary<int, int> or 15.23 MiB for HashSet<int> across the bucket and entry arrays.

Addresses the TrimExcess sizing problem discussed in #132051.

Note

This pull request description was drafted with GitHub Copilot.

tannergoodingand others added 2 commits August 10, 2026 13:36
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI lite review requested due to automatic review settings August 10, 2026 20:57
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

CopilotAI 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.

Pull request overview

Updates internal hash-table sizing helpers so Dictionary<TKey, TValue>.TrimExcess(int) and HashSet<T>.TrimExcess(int) choose a tighter “nearest valid prime” capacity (rather than the growth-oriented cached prime table), reducing retained storage after trimming while keeping the existing cached-prime behavior for construction/growth paths.

Changes:

  • Added a new prime-sizing path (GetPrimeAtLeast) and optimized prime search in System.Collections.HashHelpers.
  • Switched Dictionary/HashSetTrimExcess(int) to use the tighter prime sizing and refactored trim rehashing into compacting resize helpers.
  • Added regression tests asserting the new TrimExcess capacity selection behavior.
Show a summary per file
FileDescription
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/HashHelpers.csOptimizes prime selection in MetadataLoadContext’s local HashHelpers.
src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.csAdds GetPrimeAtLeast and updates prime-testing/search logic used by core collections.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.csUses tighter prime sizing for TrimExcess and introduces compacting resize/copy helpers.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.csUses tighter prime sizing for TrimExcess and introduces compacting resize helper.
src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.csAdds test coverage for the new HashSet.TrimExcess sizing behavior.
src/libraries/System.Collections/tests/Generic/Dictionary/Dictionary.Generic.Tests.csAdds test coverage for the new Dictionary.TrimExcess sizing behavior.

Review details

  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:09

CopilotAI 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.

Review details

  • Files reviewed: 17/17 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:49

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs Outdated
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 04:46

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 05:04
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

CopilotAI 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.

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

CopilotAI review requested due to automatic review settings August 14, 2026 14:37
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from d8ccc7f to 131ba6cCompareAugust 14, 2026 14:38
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from 131ba6c to 609a2f2CompareAugust 14, 2026 14:38

CopilotAI 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.

Review details

Suppressed comments (1)

src/libraries/Common/src/System/Collections/HashHelpers.cs:146

  • GetPrimeAtLeastCore uses an unbounded while (true) and increments candidate without any overflow/termination check. For large min values (e.g., int.MaxValue from public Dictionary.TrimExcess(int) / HashSet.TrimExcess(int)), candidate += increment can overflow to a negative value and the loop will never terminate, potentially hanging the caller.
  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@vojtechgadurek

vojtechgadurek commented Aug 14, 2026

Copy link
Copy Markdown

Hi all, I was just wondering, why we do not make the prime array denser? If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

The performance hit for searching the correct prime should be neglible to the overall cost of copy of all elements (if using linear search).

It may be noticable, if someone is allocating large dictionaries and then not using them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

This comes at other cost, including pessimizing the common case of automatic growth in favor of the less common case of explicit user sizing.

There's a lot of primes, with the largest gap being (when accounting for the HashPrime of 101) being roughly 318 between any two primes between [0, int.MaxValue] (there's roughly 465m total primes in that range, not accounting for the hash prime filtering). On the other hand, finding the next largest prime via computation is also not terribly expensive and the more expensive cost is actually allocating+copying, particularly for larger counts (somewhere around 1500x Int128 is where I measured it start to be non-impactful).

It may be noticable, if someone is allocating large dictionaries and then not using them.

Users intentionally over-allocating isn't a concern. That's on them to fix if its problematic.

@tannergooding

tannergooding commented Aug 14, 2026

Copy link
Copy Markdown
MemberAuthor

Unfortunately, there are still major problems with the current version of this PR:

I appreciate the feedback and while I've already addressed many of these statements on the other thread, I'll summarize the general response here as well.

Given effectively random hashes (which is expected for most inputs and is how most GetHashCode implementations are built), any given dictionary follows the standard 1 + ((count / capacity) / 2) algorithm (where count / capacity is effectively the load factor) for the expected average number of lookups required. So when count is approx equal to capacity, you get an expected 1.5 comparisons per lookup. When capacity is roughly double count, then it becomes 1.25; then 1.125 at 4x the count, and so on. You need capacity to be roughly 10x the count to hit 1.05.

The existing lookup table entries averages about a 1.2 growth between prime entries and so the best case scenario when using exclusively the lookup table is around 1.417 average lookups (in contrast to the 1.5 base quoted above). We could have the algorithm always pick capacity * 1.2 but then that is misleading to users and what they request explicitly and so its safer and simpler to just do the "nearest prime" and let them scale it themselves if desired.

Then, while the 1 vs 1.4 vs 1.5 vs ... average lookups follow big-O notation, that isn't necessarily meaningful and there are other aspects to be considered. This includes that at smaller n, you're actually making memory accesses more random and so likely hurting perf because you're less likely to hit the cache. There is also the aspect of GC pressure, cost of allocating, zeroing, and copying that memory, etc. So the real world consideration is very different from just looking at the raw theoretical math.

Using Guid as an example (and noting that other types will have different measurements/costs), we save 4.96 MiB at 1m entries while at 4.2m entries we see 24.4 MiB in allocating savings. The perf for these however ends up being about net neutral with it being 2-4% faster in optimal cases and around 3-6% slower in the worst case scenarios; while distinct runs fluctuate around 5% on average just due to things like loop alignment and memory alignment that you happen to be given by the GC. Showcasing that this isn't likely a meaningful scenario and the winnings are really the size savings with little impact to real world perf for that theoretical 0.08 savings on average lookups done.

This then changes nothing with regards to what users could already see/experience. That is, the perf characteristics here are entirely dependent on the count to capacity ratio. Even with the prime table picking larger than necessary primes, the actual count could end up being a load capacity that is close to 1.0 and therefore could already see that 1.5 average. If a user actually cared, they'd need to use FrozenDictionary (to try and get 1.05x-1.25x, which is its target range based on count) or to explicitly specify a larger capacity; in which case this PR improves their ability to optimize for their scenario as it gives them what they ask for.


There are few things that are true wins or true losses, most are balanced based on many factors.

This PR in particular has one easy win in improving the prime lookup perf, at the cost of more code and algorithmic complexity.

It then has a different win in allowing TrimExcess to respect the user specified size (rather than choosing something that is in up to 1.2x larger), but at the cost of meaning users explicitly sizing their dictionaries need to better ensure they're picking an appropriate size -- which again is something they already had to consider for many specified capacities, just not all of them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

This is also notably not something for .NET 11, it'd be for .NET 12; and so it's something we have essentially a full 15 months to get feedback around and to tune if needed, including if we simply want to always choose capacity * 1.2x to maintain the existing lookup table distancing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 28, 2026 15:26

CopilotAI 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.

Copilot review overview

Review tier: Lite
Findings: None

@tannergooding

Copy link
Copy Markdown
MemberAuthor

Resolved merge conflicts. @MihaZupan, @eiriktsarpalis could this get re-review.

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
@tannergooding

Copy link
Copy Markdown
MemberAuthor

/ba-g unrelated crypto test failures

@tannergooding
tannergooding merged commit 98a0a46 into dotnet:mainAug 31, 2026
130 of 134 checks passed
@tannergooding
tannergooding deleted the tannergooding-dictionary-prime-sizing branch August 31, 2026 14:56
@dotnet-milestone-botdotnet-milestone-botBot added this to the 12.0-preview1 milestone Aug 31, 2026
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants

@tannergooding@verelpode@vojtechgadurek@eiriktsarpalis@jkotas@PranavSenthilnathan@MihaZupan@hamarb123@rzikm
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Use nearest prime sizing for collection trimming - #132098

Merged
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing
Aug 31, 2026
Merged

Use nearest prime sizing for collection trimming#132098
tannergooding merged 10 commits into
dotnet:mainfrom
tannergooding:tannergooding-dictionary-prime-sizing

Conversation

@tannergooding

@tannergoodingtannergooding commented Aug 10, 2026

Copy link
Copy Markdown
Member

Dictionary<TKey, TValue> and HashSet<T> currently use the growth-oriented cached prime table for TrimExcess, which can retain nearly 20% more storage than requested. Select the nearest valid prime for compaction while preserving the existing cached-prime behavior for construction, EnsureCapacity, and automatic growth.

The shared prime-selection implementation now lives under libraries/Common rather than being duplicated by MetadataLoadContext.

Internal prime search

These are microbenchmarks of the computed-prime fallback beyond the precomputed cache. They measure the helper directly, not end-user TrimExcess performance. Visiting only 6k +/- 1 candidates and reusing the square-root limit improved representative searches by 33-36% locally:

MinimumBeforeAfter
1,00067.51 ns43.22 ns
5,001,2342.185 us1.458 us
1,000,000,00030.04 us19.85 us

TrimExcess

To isolate destination sizing from other implementation differences, these benchmarks use the PR implementation for both cases and compact to either the previous cached-prime target or the new nearest-prime target. Copy throughput is mixed within a few percent while allocation falls with the retained capacity:

CollectionCountCached targetNearest targetTime ratioAllocated beforeAllocated after
Dictionary<int, int>100,000108,631100,0031.02x2.07 MB1.91 MB
Dictionary<int, int>1,000,0001,162,6871,000,0031.03x22.18 MB19.07 MB
Dictionary<int, int>5,001,2345,999,4715,001,2510.98x114.43 MB95.39 MB
HashSet<int>100,000108,631100,0031.06x1.66 MB1.53 MB
HashSet<int>1,000,0001,162,6871,000,0030.98x17.74 MB15.26 MB
HashSet<int>5,001,2345,999,4715,001,2510.99x91.54 MB76.31 MB

At 5,001,234 entries, this avoids 998,220 slots -- approximately 19.04 MiB for Dictionary<int, int> or 15.23 MiB for HashSet<int> across the bucket and entry arrays.

Addresses the TrimExcess sizing problem discussed in #132051.

Note

This pull request description was drafted with GitHub Copilot.

tannergoodingand others added 2 commits August 10, 2026 13:36
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI lite review requested due to automatic review settings August 10, 2026 20:57
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.

CopilotAI 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.

Pull request overview

Updates internal hash-table sizing helpers so Dictionary<TKey, TValue>.TrimExcess(int) and HashSet<T>.TrimExcess(int) choose a tighter “nearest valid prime” capacity (rather than the growth-oriented cached prime table), reducing retained storage after trimming while keeping the existing cached-prime behavior for construction/growth paths.

Changes:

  • Added a new prime-sizing path (GetPrimeAtLeast) and optimized prime search in System.Collections.HashHelpers.
  • Switched Dictionary/HashSetTrimExcess(int) to use the tighter prime sizing and refactored trim rehashing into compacting resize helpers.
  • Added regression tests asserting the new TrimExcess capacity selection behavior.
Show a summary per file
FileDescription
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/HashHelpers.csOptimizes prime selection in MetadataLoadContext’s local HashHelpers.
src/libraries/System.Private.CoreLib/src/System/Collections/HashHelpers.csAdds GetPrimeAtLeast and updates prime-testing/search logic used by core collections.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.csUses tighter prime sizing for TrimExcess and introduces compacting resize/copy helpers.
src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.csUses tighter prime sizing for TrimExcess and introduces compacting resize helper.
src/libraries/System.Collections/tests/Generic/HashSet/HashSet.Generic.Tests.csAdds test coverage for the new HashSet.TrimExcess sizing behavior.
src/libraries/System.Collections/tests/Generic/Dictionary/Dictionary.Generic.Tests.csAdds test coverage for the new Dictionary.TrimExcess sizing behavior.

Review details

  • Files reviewed: 6/6 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:09

CopilotAI 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.

Review details

  • Files reviewed: 17/17 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 10, 2026 21:49

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs Outdated
Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 04:46

CopilotAI 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.

Review details

  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 11, 2026 05:04
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

CopilotAI 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.

Review details

  • Files reviewed: 19/19 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

CopilotAI review requested due to automatic review settings August 14, 2026 14:37
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from d8ccc7f to 131ba6cCompareAugust 14, 2026 14:38
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@tannergooding
tannergoodingforce-pushed the tannergooding-dictionary-prime-sizing branch from 131ba6c to 609a2f2CompareAugust 14, 2026 14:38

CopilotAI 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.

Review details

Suppressed comments (1)

src/libraries/Common/src/System/Collections/HashHelpers.cs:146

  • GetPrimeAtLeastCore uses an unbounded while (true) and increments candidate without any overflow/termination check. For large min values (e.g., int.MaxValue from public Dictionary.TrimExcess(int) / HashSet.TrimExcess(int)), candidate += increment can overflow to a negative value and the loop will never terminate, potentially hanging the caller.
  • Files reviewed: 18/18 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@vojtechgadurek

vojtechgadurek commented Aug 14, 2026

Copy link
Copy Markdown

Hi all, I was just wondering, why we do not make the prime array denser? If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

The performance hit for searching the correct prime should be neglible to the overall cost of copy of all elements (if using linear search).

It may be noticable, if someone is allocating large dictionaries and then not using them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

If we increase the size 10 times, we should lower the overhead to 1/10 of the current.

This comes at other cost, including pessimizing the common case of automatic growth in favor of the less common case of explicit user sizing.

There's a lot of primes, with the largest gap being (when accounting for the HashPrime of 101) being roughly 318 between any two primes between [0, int.MaxValue] (there's roughly 465m total primes in that range, not accounting for the hash prime filtering). On the other hand, finding the next largest prime via computation is also not terribly expensive and the more expensive cost is actually allocating+copying, particularly for larger counts (somewhere around 1500x Int128 is where I measured it start to be non-impactful).

It may be noticable, if someone is allocating large dictionaries and then not using them.

Users intentionally over-allocating isn't a concern. That's on them to fix if its problematic.

@tannergooding

tannergooding commented Aug 14, 2026

Copy link
Copy Markdown
MemberAuthor

Unfortunately, there are still major problems with the current version of this PR:

I appreciate the feedback and while I've already addressed many of these statements on the other thread, I'll summarize the general response here as well.

Given effectively random hashes (which is expected for most inputs and is how most GetHashCode implementations are built), any given dictionary follows the standard 1 + ((count / capacity) / 2) algorithm (where count / capacity is effectively the load factor) for the expected average number of lookups required. So when count is approx equal to capacity, you get an expected 1.5 comparisons per lookup. When capacity is roughly double count, then it becomes 1.25; then 1.125 at 4x the count, and so on. You need capacity to be roughly 10x the count to hit 1.05.

The existing lookup table entries averages about a 1.2 growth between prime entries and so the best case scenario when using exclusively the lookup table is around 1.417 average lookups (in contrast to the 1.5 base quoted above). We could have the algorithm always pick capacity * 1.2 but then that is misleading to users and what they request explicitly and so its safer and simpler to just do the "nearest prime" and let them scale it themselves if desired.

Then, while the 1 vs 1.4 vs 1.5 vs ... average lookups follow big-O notation, that isn't necessarily meaningful and there are other aspects to be considered. This includes that at smaller n, you're actually making memory accesses more random and so likely hurting perf because you're less likely to hit the cache. There is also the aspect of GC pressure, cost of allocating, zeroing, and copying that memory, etc. So the real world consideration is very different from just looking at the raw theoretical math.

Using Guid as an example (and noting that other types will have different measurements/costs), we save 4.96 MiB at 1m entries while at 4.2m entries we see 24.4 MiB in allocating savings. The perf for these however ends up being about net neutral with it being 2-4% faster in optimal cases and around 3-6% slower in the worst case scenarios; while distinct runs fluctuate around 5% on average just due to things like loop alignment and memory alignment that you happen to be given by the GC. Showcasing that this isn't likely a meaningful scenario and the winnings are really the size savings with little impact to real world perf for that theoretical 0.08 savings on average lookups done.

This then changes nothing with regards to what users could already see/experience. That is, the perf characteristics here are entirely dependent on the count to capacity ratio. Even with the prime table picking larger than necessary primes, the actual count could end up being a load capacity that is close to 1.0 and therefore could already see that 1.5 average. If a user actually cared, they'd need to use FrozenDictionary (to try and get 1.05x-1.25x, which is its target range based on count) or to explicitly specify a larger capacity; in which case this PR improves their ability to optimize for their scenario as it gives them what they ask for.


There are few things that are true wins or true losses, most are balanced based on many factors.

This PR in particular has one easy win in improving the prime lookup perf, at the cost of more code and algorithmic complexity.

It then has a different win in allowing TrimExcess to respect the user specified size (rather than choosing something that is in up to 1.2x larger), but at the cost of meaning users explicitly sizing their dictionaries need to better ensure they're picking an appropriate size -- which again is something they already had to consider for many specified capacities, just not all of them.

@tannergooding

Copy link
Copy Markdown
MemberAuthor

This is also notably not something for .NET 11, it'd be for .NET 12; and so it's something we have essentially a full 15 months to get feedback around and to tune if needed, including if we simply want to always choose capacity * 1.2x to maintain the existing lookup table distancing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CopilotAI review requested due to automatic review settings August 28, 2026 15:26

CopilotAI 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.

Copilot review overview

Review tier: Lite
Findings: None

@tannergooding

Copy link
Copy Markdown
MemberAuthor

Resolved merge conflicts. @MihaZupan, @eiriktsarpalis could this get re-review.

Comment threadsrc/libraries/Common/src/System/Collections/HashHelpers.cs
@tannergooding

Copy link
Copy Markdown
MemberAuthor

/ba-g unrelated crypto test failures

@tannergooding
tannergooding merged commit 98a0a46 into dotnet:mainAug 31, 2026
130 of 134 checks passed
@tannergooding
tannergooding deleted the tannergooding-dictionary-prime-sizing branch August 31, 2026 14:56
@dotnet-milestone-botdotnet-milestone-botBot added this to the 12.0-preview1 milestone Aug 31, 2026
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants

@tannergooding@verelpode@vojtechgadurek@eiriktsarpalis@jkotas@PranavSenthilnathan@MihaZupan@hamarb123@rzikm