Skip to content

Commit 390c55b

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

1 file changed

Lines changed: 56 additions & 7 deletions

File tree

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

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

378-
var otherSet = new SortedSet<T>(other, this.KeyComparer);
379-
if (this.Count != otherSet.Count)
378+
if (other is ICollection<T> otherAsICollection && otherAsICollection.Count < this.Count)
380379
{
381380
return false;
382381
}
383382

384-
int matches = 0;
385-
foreach (T item in otherSet)
383+
else if (other is IReadOnlyCollection<T> otherAsIReadOnlyCollection && otherAsIReadOnlyCollection.Count < this.Count)
386384
{
387-
if (!this.Contains(item))
385+
return false;
386+
}
387+
388+
if (other is ImmutableSortedSet<T> otherAsImmutableSortedSet && otherAsImmutableSortedSet.KeyComparer == this.KeyComparer)
389+
{
390+
if (otherAsImmutableSortedSet.Count != this.Count)
388391
{
389392
return false;
390393
}
394+
using var otherAsImmutableSortedSetEnumerator = otherAsImmutableSortedSet.GetEnumerator();
395+
using (var thisEnumerator = this.GetEnumerator())
396+
{
397+
while (otherAsImmutableSortedSetEnumerator.MoveNext() && thisEnumerator.MoveNext())
398+
{
399+
if (this.KeyComparer.Compare(otherAsImmutableSortedSetEnumerator.Current, thisEnumerator.Current) != 0)
400+
{
401+
return false;
402+
}
403+
}
404+
}
405+
return true;
406+
}
391407

392-
matches++;
408+
else if (other is SortedSet<T> otherAsSortedSet && otherAsSortedSet.Comparer == this.KeyComparer)
409+
{
410+
if (otherAsSortedSet.Count != this.Count)
411+
{
412+
return false;
413+
}
414+
using var otherAsSortedSetEnumerator = otherAsSortedSet.GetEnumerator();
415+
using (var thisEnumerator = this.GetEnumerator())
416+
{
417+
while (otherAsSortedSetEnumerator.MoveNext() && thisEnumerator.MoveNext())
418+
{
419+
if (this.KeyComparer.Compare(otherAsSortedSetEnumerator.Current, thisEnumerator.Current) != 0)
420+
{
421+
return false;
422+
}
423+
}
424+
}
425+
return true;
393426
}
394427

395-
return matches == this.Count;
428+
var otherSet = new SortedSet<T>(other, this.KeyComparer);
429+
if (this.Count != otherSet.Count)
430+
{
431+
return false;
432+
}
433+
using var otherSetEnumerator = otherSet.GetEnumerator();
434+
using (var thisEnumerator = this.GetEnumerator())
435+
{
436+
while (otherSetEnumerator.MoveNext() && thisEnumerator.MoveNext())
437+
{
438+
if (this.KeyComparer.Compare(otherSetEnumerator.Current, thisEnumerator.Current) != 0)
439+
{
440+
return false;
441+
}
442+
}
443+
}
444+
return true;
396445
}
397446

398447
/// <summary>

0 commit comments

Comments
 (0)