Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit c340cd3

Browse files
benaadamsstephentoub
authored andcommitted
Improve Dictionary FindEntry CQ
Signed-off-by: dotnet-bot-corefx-mirror <dotnet-bot@microsoft.com>
1 parent 02b5689 commit c340cd3

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

src/Common/src/CoreLib/System/Collections/Generic/Dictionary.cs

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -362,15 +362,28 @@ private int FindEntry(TKey key)
362362
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
363363
}
364364

365-
if (_buckets != null)
365+
int[] buckets = _buckets;
366+
int i = -1;
367+
if (buckets != null)
366368
{
367-
int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF;
368-
for (int i = _buckets[hashCode % _buckets.Length]; i >= 0; i = _entries[i].next)
369+
IEqualityComparer<TKey> comparer = _comparer;
370+
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
371+
i = buckets[hashCode % buckets.Length];
372+
373+
Entry[] entries = _entries;
374+
do
369375
{
370-
if (_entries[i].hashCode == hashCode && _comparer.Equals(_entries[i].key, key)) return i;
371-
}
376+
// Should be a while loop https://github.com/dotnet/coreclr/issues/15476
377+
// Test in if to drop range check for following array access
378+
if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)))
379+
{
380+
break;
381+
}
382+
383+
i = entries[i].next;
384+
} while (true);
372385
}
373-
return -1;
386+
return i;
374387
}
375388

376389
private int Initialize(int capacity)

0 commit comments

Comments
 (0)