Skip to content

Commit a8b2c92

Browse files
authored
Reduce redundant lookup in OrderedDictionary<TKey, TValue>.Remove (#128988)
This PR reduces a redundant lookup in `OrderedDictionary<TKey, TValue>.Remove(KeyValuePair<TKey, TValue>)` by using the index obtained from `TryGetValue` to call `RemoveAt`. I also removed a duplicated null check in `IDictionary.Add`.
1 parent 055beba commit a8b2c92

1 file changed

Lines changed: 10 additions & 9 deletions

File tree

src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1218,10 +1218,16 @@ void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[]
12181218
}
12191219

12201220
/// <inheritdoc/>
1221-
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) =>
1222-
TryGetValue(item.Key, out TValue? value) &&
1223-
EqualityComparer<TValue>.Default.Equals(value, item.Value) &&
1224-
Remove(item.Key);
1221+
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
1222+
{
1223+
if (TryGetValue(item.Key, out TValue? value, out int index) && EqualityComparer<TValue>.Default.Equals(value, item.Value))
1224+
{
1225+
RemoveAt(index);
1226+
return true;
1227+
}
1228+
1229+
return false;
1230+
}
12251231

12261232
/// <inheritdoc/>
12271233
void IDictionary.Add(object key, object? value)
@@ -1237,11 +1243,6 @@ void IDictionary.Add(object key, object? value)
12371243
throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key));
12381244
}
12391245

1240-
if (default(TValue) is not null)
1241-
{
1242-
ArgumentNullException.ThrowIfNull(value);
1243-
}
1244-
12451246
TValue tvalue = default!;
12461247
if (value is not null)
12471248
{

0 commit comments

Comments
 (0)