From d6c7725be042038003ab13588f0a44acdf356201 Mon Sep 17 00:00:00 2001 From: Denis Petukhov Date: Wed, 26 Aug 2026 00:24:26 +0300 Subject: [PATCH] Add fast path for Overlaps when other is HashSet with same equality comparer and has more items --- .../src/System/Collections/Generic/HashSet.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs index 34756784e28b91..43d19da2f9e785 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs @@ -1114,6 +1114,20 @@ public bool Overlaps(IEnumerable other) return true; } + // Fast path for Overlaps when other is HashSet with same equality comparer and has more items + if (other is HashSet otherAsSet && EqualityComparersAreEqual(this, otherAsSet) && otherAsSet.Count > Count) + { + foreach (T element in this) + { + if (otherAsSet.Contains(element)) + { + return true; + } + } + + return false; + } + foreach (T element in other) { if (Contains(element))