Skip to content

Commit 620017b

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

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

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

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

746+
if (other is ICollection<T> otherAsICollectionGeneric)
747+
{
748+
if (otherAsICollectionGeneric.Count < origin.Count)
749+
{
750+
return false;
751+
}
752+
if (other is HashSet<T> otherAsHashSet)
753+
{
754+
if (otherAsHashSet.Comparer == origin.EqualityComparer)
755+
{
756+
if (otherAsHashSet.Count != origin.Count)
757+
{
758+
return false;
759+
}
760+
foreach (T item in otherAsHashSet)
761+
{
762+
if (!Contains(item, origin))
763+
{
764+
return false;
765+
}
766+
}
767+
return true;
768+
}
769+
}
770+
else if (other is ImmutableHashSet<T> otherAsImmutableHashSet)
771+
{
772+
if (otherAsImmutableHashSet.KeyComparer == origin.EqualityComparer)
773+
{
774+
if (otherAsImmutableHashSet.Count != origin.Count)
775+
{
776+
return false;
777+
}
778+
foreach (T item in otherAsImmutableHashSet)
779+
{
780+
if (!Contains(item, origin))
781+
{
782+
return false;
783+
}
784+
}
785+
return true;
786+
}
787+
}
788+
}
789+
else if (other is ICollection otherAsICollection)
790+
{
791+
if (otherAsICollection.Count < origin.Count)
792+
{
793+
return false;
794+
}
795+
}
746796
var otherSet = new HashSet<T>(other, origin.EqualityComparer);
747797
if (origin.Count != otherSet.Count)
748798
{

0 commit comments

Comments
 (0)