From 40fc408f5782968107b2d23f4643af9da93f9cdb Mon Sep 17 00:00:00 2001 From: Ben Adams Date: Mon, 11 Dec 2017 02:19:19 +0000 Subject: [PATCH 1/2] Improve Dictionary FindEntry CQ --- .../System/Collections/Generic/Dictionary.cs | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/mscorlib/shared/System/Collections/Generic/Dictionary.cs b/src/mscorlib/shared/System/Collections/Generic/Dictionary.cs index 4f342752d837..fb831737d416 100644 --- a/src/mscorlib/shared/System/Collections/Generic/Dictionary.cs +++ b/src/mscorlib/shared/System/Collections/Generic/Dictionary.cs @@ -362,15 +362,26 @@ private int FindEntry(TKey key) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } - if (_buckets != null) + int[] buckets = _buckets; + int i = -1; + if (buckets != null) { - int hashCode = _comparer.GetHashCode(key) & 0x7FFFFFFF; - for (int i = _buckets[hashCode % _buckets.Length]; i >= 0; i = _entries[i].next) + IEqualityComparer comparer = _comparer; + int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; + i = buckets[hashCode % buckets.Length]; + + Entry[] entries = _entries; + while (i >= 0) { - if (_entries[i].hashCode == hashCode && _comparer.Equals(_entries[i].key, key)) return i; + if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) + { + break; + } + + i = entries[i].next; } } - return -1; + return i; } private void Initialize(int capacity) From 25dd8d9c8d38ded111436ef3a46ce10fb33b003c Mon Sep 17 00:00:00 2001 From: Ben Adams Date: Fri, 15 Dec 2017 04:30:19 +0000 Subject: [PATCH 2/2] Drop range check --- .../shared/System/Collections/Generic/Dictionary.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/mscorlib/shared/System/Collections/Generic/Dictionary.cs b/src/mscorlib/shared/System/Collections/Generic/Dictionary.cs index fb831737d416..9e3a483d91bf 100644 --- a/src/mscorlib/shared/System/Collections/Generic/Dictionary.cs +++ b/src/mscorlib/shared/System/Collections/Generic/Dictionary.cs @@ -371,15 +371,17 @@ private int FindEntry(TKey key) i = buckets[hashCode % buckets.Length]; Entry[] entries = _entries; - while (i >= 0) + do { - if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) + // Should be a while loop https://github.com/dotnet/coreclr/issues/15476 + // Test in if to drop range check for following array access + if ((uint)i >= (uint)entries.Length || (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))) { break; } i = entries[i].next; - } + } while (true); } return i; }