Skip to content

Commit 41c75bf

Browse files
author
Ahmed
committed
Optimize ImmutableSortedSet<T>.SetEquals to avoid unnecessary allocations
1 parent 874cab5 commit 41c75bf

File tree

1 file changed

+43
-6
lines changed

1 file changed

+43
-6
lines changed

src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -375,24 +375,61 @@ public bool SetEquals(IEnumerable<T> other)
375375
return true;
376376
}
377377

378+
if (other is ICollection<T> otherAsICollection && otherAsICollection.Count < this.Count)
379+
{
380+
return false;
381+
}
382+
383+
else if (other is IReadOnlyCollection<T> otherAsIReadOnlyCollection && otherAsIReadOnlyCollection.Count < this.Count)
384+
{
385+
return false;
386+
}
387+
388+
if (other is ImmutableSortedSet<T> otherAsImmutableSortedSet && otherAsImmutableSortedSet.KeyComparer == this.KeyComparer)
389+
{
390+
if (otherAsImmutableSortedSet.Count != this.Count)
391+
{
392+
return false;
393+
}
394+
foreach (T item in otherAsImmutableSortedSet)
395+
{
396+
if (!this.Contains(item))
397+
{
398+
return false;
399+
}
400+
}
401+
return true;
402+
}
403+
404+
else if (other is SortedSet<T> otherAsSortedSet && otherAsSortedSet.Comparer == this.KeyComparer)
405+
{
406+
if (otherAsSortedSet.Count != this.Count)
407+
{
408+
return false;
409+
}
410+
foreach (T item in otherAsSortedSet)
411+
{
412+
if (!this.Contains(item))
413+
{
414+
return false;
415+
}
416+
}
417+
return true;
418+
}
419+
378420
var otherSet = new SortedSet<T>(other, this.KeyComparer);
379421
if (this.Count != otherSet.Count)
380422
{
381423
return false;
382424
}
383-
384-
int matches = 0;
385425
foreach (T item in otherSet)
386426
{
387427
if (!this.Contains(item))
388428
{
389429
return false;
390430
}
391-
392-
matches++;
393431
}
394-
395-
return matches == this.Count;
432+
return true;
396433
}
397434

398435
/// <summary>

0 commit comments

Comments
 (0)