Pattern: Missing use of ContainsKey()
/ContainsValue()
Issue: -
Calling Contains
on the Keys
or Values collection can often be more expensive than calling ContainsKey
or ContainsValue
on the dictionary itself:
- Many dictionary implementations lazily instantiate the key and value collections, which means that accessing the
Keys
orValues
collection may result in extra allocations. - You may end up calling an extension method on
IEnumerable<T>
if the keys or values collection uses explicit interface implementation to hide methods onICollection<T>
. This can lead to reduced performance, especially when accessing the key collection. Most dictionary implementations are able to provide a fast O(1) containment check for keys, while theContains
extension method onIEnumerable<T>
usually does a slow O(n) containment check.
Example of incorrect code:
var dictionary = new Dictionary<string, int>();
dictionary.Values.Contains(17);
Example of correct code:
var dictionary = new Dictionary<string, int>();
dictionary.ContainsValue(17);