IDictionary<TK, TV>
defines method IDictionary.ContainsKey(in TK)
and property IDictionary.Keys
(of type ICollection
).
I'm interested in (asymptotic) complexity of this method and property in Dictionary
implementation of IDictionary<TK, TV>
.
Consider definitions
IDictionary<int, string> dict = new Dictionary<int, string>();
int k = new Random().Next();
and consider that we have added to the dictionary dict
n
unique KeyValuePair
s.
What is expected (asymptotic) complexity of a call dict.ContainsKey(k)
? I hope it's in O(1)
but I did not find it in documentation of Dictionary.ContainsKey
.
What is expected (asymptotic) complexity of call dict.Keys.Contains(k)
? I hope it's in O(1)
but I did not find it in documentation of Dictionary.Keys
nor in documentation of Dictionary.KeyCollection
. If it is in O(1)
I don't understand why type of IDictionary.Keys
property is ICollection
and not ISet
(like in Java for example).
Since
IDictionary<K,V>
is only an interface, not an implementation, then it doesn't provide any performance guarantees.For the built-in
Dictionary<K,V>
type, theContainsKey
method should be O(1):The
Keys.Contains
method actually calls the parent dictionary'sContainsKey
method, so that should also be O(1):(Both quotes are taken from the "Remarks" section of the relevant documentation pages.)
The first link you provided says, in the Remarks:
Also, if you click on the
Contains
method you'll see the same thing in the remarks: