Skip to content

Commit 5f2749e

Browse files
AhmedAhmed
authored andcommitted
Optimize ImmutableHashSet<T>.SetEquals to avoid unnecessary allocations
1 parent 874cab5 commit 5f2749e

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

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

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -743,19 +743,33 @@ private static bool SetEquals(IEnumerable<T> other, MutationInput origin)
743743
{
744744
Requires.NotNull(other, nameof(other));
745745

746-
var otherSet = new HashSet<T>(other, origin.EqualityComparer);
747-
if (origin.Count != otherSet.Count)
746+
if (other is ImmutableHashSet<T> ImmutableHashSet && ImmutableHashSet.KeyComparer == origin.EqualityComparer)
748747
{
749-
return false;
748+
if (ImmutableHashSet.Count != origin.Count) return false;
749+
foreach (T item in ImmutableHashSet)
750+
{
751+
if (!Contains(item, origin)) return false;
752+
}
753+
return true;
750754
}
751755

752-
foreach (T item in otherSet)
756+
else if (other is HashSet<T> hashSet && hashSet.Comparer == origin.EqualityComparer)
753757
{
754-
if (!Contains(item, origin))
758+
if (hashSet.Count != origin.Count) return false;
759+
foreach (T item in hashSet)
755760
{
756-
return false;
761+
if (!Contains(item, origin)) return false;
757762
}
763+
return true;
758764
}
765+
766+
var otherSet = new HashSet<T>(other, origin.EqualityComparer);
767+
if (otherSet.Count != origin.Count) return false;
768+
foreach (T item in otherSet)
769+
{
770+
if (!Contains(item, origin)) return false;
771+
}
772+
759773
return true;
760774
}
761775

0 commit comments

Comments
 (0)