Skip to content

Commit 827bfda

Browse files
Ahmedaw0lid
authored andcommitted
Optimize ImmutableSortedSet<T>.SetEquals to avoid unnecessary allocations
1 parent 18290ad commit 827bfda

1 file changed

Lines changed: 21 additions & 12 deletions

File tree

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

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -370,29 +370,38 @@ public bool SetEquals(IEnumerable<T> other)
370370
{
371371
Requires.NotNull(other, nameof(other));
372372

373-
if (object.ReferenceEquals(this, other))
373+
if (object.ReferenceEquals(this, other)) return true;
374+
375+
if (other is ImmutableSortedSet<T> immutableSortedSet && immutableSortedSet.KeyComparer == this.KeyComparer)
374376
{
377+
if (immutableSortedSet.Count != this.Count) return false;
378+
foreach (T item in immutableSortedSet)
379+
{
380+
if (!this.Contains(item)) return false;
381+
}
382+
375383
return true;
376384
}
377385

378-
var otherSet = new SortedSet<T>(other, this.KeyComparer);
379-
if (this.Count != otherSet.Count)
386+
else if (other is SortedSet<T> sortedSet && sortedSet.Comparer == this.KeyComparer)
380387
{
381-
return false;
388+
if (sortedSet.Count != this.Count) return false;
389+
foreach (T item in sortedSet)
390+
{
391+
if (!this.Contains(item)) return false;
392+
}
393+
394+
return true;
382395
}
383396

384-
int matches = 0;
397+
var otherSet = new SortedSet<T>(other, this.KeyComparer);
398+
if (otherSet.Count != this.Count) return false;
385399
foreach (T item in otherSet)
386400
{
387-
if (!this.Contains(item))
388-
{
389-
return false;
390-
}
391-
392-
matches++;
401+
if (!this.Contains(item)) return false;
393402
}
394403

395-
return matches == this.Count;
404+
return true;
396405
}
397406

398407
/// <summary>

0 commit comments

Comments
 (0)