From 87bd1fa32502d94088bc7e227d5c28a92b2a3620 Mon Sep 17 00:00:00 2001 From: prozolic <42107886+prozolic@users.noreply.github.com> Date: Thu, 4 Jun 2026 23:14:42 +0900 Subject: [PATCH] Reduce redundant lookup in OrderedDictionary.Remove Reduce a redundant lookup in `OrderedDictionary.Remove(KeyValuePair)` by using the index obtained from `TryGetValue` to call `RemoveAt`. Also remove a duplicated null check in `IDictionary.Add`. --- .../Collections/Generic/OrderedDictionary.cs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs b/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs index 58d8f2e4fef46f..0bacc72b32f4d3 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs @@ -1218,10 +1218,16 @@ void ICollection>.CopyTo(KeyValuePair[] } /// - bool ICollection>.Remove(KeyValuePair item) => - TryGetValue(item.Key, out TValue? value) && - EqualityComparer.Default.Equals(value, item.Value) && - Remove(item.Key); + bool ICollection>.Remove(KeyValuePair item) + { + if (TryGetValue(item.Key, out TValue? value, out int index) && EqualityComparer.Default.Equals(value, item.Value)) + { + RemoveAt(index); + return true; + } + + return false; + } /// void IDictionary.Add(object key, object? value) @@ -1237,11 +1243,6 @@ void IDictionary.Add(object key, object? value) throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key)); } - if (default(TValue) is not null) - { - ArgumentNullException.ThrowIfNull(value); - } - TValue tvalue = default!; if (value is not null) {