Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid allocating HashSet in Distinct() for some counts #97845

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 42 additions & 3 deletions src/libraries/System.Linq/src/System/Linq/Distinct.SpeedOpt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,50 @@ public static partial class Enumerable
{
private sealed partial class DistinctIterator<TSource> : IIListProvider<TSource>
{
public TSource[] ToArray() => Enumerable.HashSetToArray(new HashSet<TSource>(_source, _comparer));
public TSource[] ToArray()
{
if (TryGetNonEnumeratedCount(_source, out int count) && count < 2)
Copy link
Member

Choose a reason for hiding this comment

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

Optimizing for counted sources of size < 2 seems somewhat niche to me, is it worth the added type tests?

{
if (count == 1)
{
return [_source.First()];
}

public List<TSource> ToList() => new List<TSource>(new HashSet<TSource>(_source, _comparer));
return [];
}

public int GetCount(bool onlyIfCheap) => onlyIfCheap ? -1 : new HashSet<TSource>(_source, _comparer).Count;
return HashSetToArray(new HashSet<TSource>(_source, _comparer));
}

public List<TSource> ToList()
{
if (TryGetNonEnumeratedCount(_source, out int count) && count < 2)
{
if (count == 1)
{
return new List<TSource>(1) { _source.First() };
}

return [];
}

return new List<TSource>(new HashSet<TSource>(_source, _comparer));
}

public int GetCount(bool onlyIfCheap)
{
if (TryGetNonEnumeratedCount(_source, out int count) && count < 2)
{
return count;
}

if (onlyIfCheap)
{
return -1;
}

return new HashSet<TSource>(_source, _comparer).Count;
}
}
}
}
Loading