I want to use string as a key type in a Dictionary. Like Dictionary<string, string>
.
As I understand, if I want to Add a new object, it first calculate a hashcode of the key. So the complexity of Add method boils down to a complexity of String.GetHashCode()
method.
What I can't get is how can it be O(1) if to calculate it we still need to iterate through all the characters?
In short, my question is around: does adding a very long string work as quick as adding an empty string, another words does time to insert an element depends on the length of the inserted key (string type)?
I think you are mixing up the complexities regarding the insertion into the dictionary and the hash calculation of the key of the dictionary.
String.GetHashCode()
is O(n) in regards to the length of the string (hash code calculation), but a O(1) step in regards to the overall insertion operation into the dictionary, since you do not have to iterate over the elements of the dictionary.
You wrote "...and then compares it against already existing"
, there is no need to do that, you would override an existing value anyway. Once the hash is calculated, the key and value can simply be inserted into the dictionary at O(1).
(As pointed out in the comments, one exception is if the capacity of the dictionary increases, then the internal array must be re-allocated and the insertion becomes an O(n) operation.)