Skip to content

Files

Latest commit

 

History

History
29 lines (18 loc) · 1.21 KB

File metadata and controls

29 lines (18 loc) · 1.21 KB

Pattern: Missing use of ContainsKey()/ContainsValue()

Issue: -

Description

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 or Values 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 on ICollection<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 the Contains extension method on IEnumerable<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);

Further Reading