Skip to content

Commit 1ae37a5

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

File tree

1 file changed

+35
-7
lines changed

1 file changed

+35
-7
lines changed

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

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

378+
if (other is ImmutableSortedSet<T> immutableSortedSet && immutableSortedSet.KeyComparer == this.KeyComparer)
379+
{
380+
if (immutableSortedSet.Count != this.Count)
381+
{
382+
return false;
383+
}
384+
foreach (T item in immutableSortedSet)
385+
{
386+
if (!this.Contains(item))
387+
{
388+
return false;
389+
}
390+
}
391+
392+
return true;
393+
}
394+
395+
else if (other is SortedSet<T> sortedSet && sortedSet.Comparer == this.KeyComparer)
396+
{
397+
if (sortedSet.Count != this.Count)
398+
{
399+
return false;
400+
}
401+
foreach (T item in sortedSet)
402+
{
403+
if (!this.Contains(item))
404+
{
405+
return false;
406+
}
407+
}
408+
return true;
409+
}
410+
378411
var otherSet = new SortedSet<T>(other, this.KeyComparer);
379-
if (this.Count != otherSet.Count)
412+
if (otherSet.Count != this.Count)
380413
{
381414
return false;
382415
}
383-
384-
int matches = 0;
385416
foreach (T item in otherSet)
386417
{
387418
if (!this.Contains(item))
388419
{
389420
return false;
390421
}
391-
392-
matches++;
393422
}
394-
395-
return matches == this.Count;
423+
return true;
396424
}
397425

398426
/// <summary>

0 commit comments

Comments
 (0)