Skip to content

Skip clearing reference-free HashSet entries - #137582

Merged
jkotas merged 1 commit into
dotnet:mainfrom
prozolic:hashset-clear
Nov 15, 2026
Merged

jkotas merged 1 commit into
dotnet:mainfrom
prozolic:hashset-clear

Conversation

@prozolic

Copy link
Copy Markdown
Contributor

This PR uses the optimization pattern used in #136605.

In HashSet<T>.Clear, call Array.Clear on the _entries field only when RuntimeHelpers.IsReferenceOrContainsReferences<Entry>() returns true.

Benchmark

Method Job Toolchain N Mean Error StdDev Median Ratio RatioSD
Int Job-JVSFQJ \main\corerun.exe 1 3.932 ns 0.3690 ns 0.3452 ns 3.906 ns 1.00 0.00
Int Job-DXUJIM \pr\corerun.exe 1 2.604 ns 0.3410 ns 0.3189 ns 2.344 ns 0.67 0.10
String Job-JVSFQJ \main\corerun.exe 1 4.269 ns 0.7427 ns 0.6584 ns 4.102 ns 1.00 0.00
String Job-DXUJIM \pr\corerun.exe 1 4.074 ns 0.3753 ns 0.3327 ns 4.102 ns 0.97 0.16
Int Job-JVSFQJ \main\corerun.exe 16 9.766 ns 0.7730 ns 0.6852 ns 9.570 ns 1.00 0.00
Int Job-DXUJIM \pr\corerun.exe 16 6.055 ns 0.2286 ns 0.2027 ns 6.055 ns 0.62 0.04
String Job-JVSFQJ \main\corerun.exe 16 11.328 ns 1.5935 ns 1.4126 ns 10.742 ns 1.00 0.00
String Job-DXUJIM \pr\corerun.exe 16 11.589 ns 1.4779 ns 1.3824 ns 10.938 ns 1.04 0.16
Int Job-JVSFQJ \main\corerun.exe 1024 496.735 ns 39.0374 ns 34.6056 ns 483.594 ns 1.00 0.00
Int Job-DXUJIM \pr\corerun.exe 1024 104.748 ns 5.5575 ns 4.6407 ns 104.688 ns 0.21 0.02
String Job-JVSFQJ \main\corerun.exe 1024 529.808 ns 29.3214 ns 24.4847 ns 523.828 ns 1.00 0.00
String Job-DXUJIM \pr\corerun.exe 1024 638.854 ns 199.2462 ns 186.3750 ns 525.000 ns 1.21 0.35
Int Job-JVSFQJ \main\corerun.exe 65536 67,174.249 ns 456.0066 ns 380.7861 ns 67,108.984 ns 1.00 0.00
Int Job-DXUJIM \pr\corerun.exe 65536 18,845.373 ns 1,070.6758 ns 894.0627 ns 18,999.219 ns 0.28 0.01
String Job-JVSFQJ \main\corerun.exe 65536 90,035.324 ns 1,691.6398 ns 1,499.5946 ns 90,284.961 ns 1.00 0.00
String Job-DXUJIM \pr\corerun.exe 65536 90,911.049 ns 2,412.0660 ns 2,138.2337 ns 91,561.523 ns 1.01 0.03
Benchmark source (generated with Claude Code)
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);

public class ClearOnly
{
    private const int SetCount = 256;

    [Params(1, 16, 1024, 65536)]
    public int N;

    private HashSet<int>[] _int;
    private HashSet<string>[] _string;
    private string[] _strings;

    [GlobalSetup(Target = nameof(Int))]
    public void SetupInt()
    {
        _int = new HashSet<int>[SetCount];
        for (int s = 0; s < SetCount; s++) _int[s] = new HashSet<int>(N);
    }

    [GlobalSetup(Target = nameof(String))]
    public void SetupString()
    {
        _string = new HashSet<string>[SetCount];
        for (int s = 0; s < SetCount; s++) _string[s] = new HashSet<string>(N);
        _strings = new string[N];
        for (int i = 0; i < N; i++) _strings[i] = i.ToString();
    }

    [IterationSetup(Target = nameof(Int))]
    public void FillInt()
    {
        foreach (HashSet<int> set in _int)
            for (int i = 0; i < N; i++) set.Add(i);
    }

    [IterationSetup(Target = nameof(String))]
    public void FillString()
    {
        foreach (HashSet<string> set in _string)
            foreach (string item in _strings) set.Add(item);
    }

    [Benchmark(OperationsPerInvoke = SetCount)]
    public void Int()
    {
        foreach (HashSet<int> set in _int) set.Clear();
    }

    [Benchmark(OperationsPerInvoke = SetCount)]
    public void String()
    {
        foreach (HashSet<string> set in _string) set.Clear();
    }
}

In HashSet<T>.Clear, call Array.Clear on the _entries field only when
RuntimeHelpers.IsReferenceOrContainsReferences<Entry>() returns true.
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 15, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 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.

@jkotas jkotas added the tenet-performance Performance related issue label Nov 15, 2026
@jkotas
jkotas requested a balanced review from Copilot November 15, 2026 17:12

Copilot AI 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.

🟢 Approval recommended

No active review issues are reported for the reference-free HashSet clearing optimization.

No open issues 🎉

What changed in this PR

Applies the reference-free clearing optimization from Dictionary PR #136605 to HashSet<T>, avoiding unnecessary entry-array writes while retaining clearing for entries that contain managed references.

Changes:

  • Guards entry-array clearing with RuntimeHelpers.IsReferenceOrContainsReferences<Entry>(), preserving bucket and count resets.
  • Adds repeated clear-and-refill tests covering removed entries, capacity preservation, lookup results, and existing enumerators.
File Description
src/​libraries/​System.Private.CoreLib/​src/​System/​Collections/​Generic/​HashSet.cs Skips clearing reference-free entries and documents why reuse remains safe.
src/​libraries/​System.Collections/​tests/​Generic/​HashSet/​HashSet.Generic.Tests.cs Adds clear-and-refill coverage across several set sizes.

Review effort: Balanced

@jkotas

jkotas commented Nov 15, 2026

Copy link
Copy Markdown
Member

/ba-g opened #137589 on the build failure

@jkotas
jkotas merged commit 42b1043 into dotnet:main Nov 15, 2026
116 of 121 checks passed
@prozolic
prozolic deleted the hashset-clear branch November 16, 2026 12:13
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Collections community-contribution Indicates that the PR has been added by a community member tenet-performance Performance related issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants