When you're performing Big-O analysis you need to be very clear what the variables are. Oftentimes the n is left undefined, or implied, but it's crucial to know what exactly it is.
- Let's define n as the number of items in the hash map.
When n is the only variable under consideration then all of the methods are O(1). None of them loops over this.list, and so all operate in constant time with respect to the number of items in the hash map.
But, you object: there's a loop in hash(). How can it be O(1). Well, what is it looping over? Is it looping over the other items in the map? No. It's looping over input—but input.length is not a variable we're considering.
When people analyze hash map performance they normally ignore the length of the strings being passed in. If we do that, then with respect to n hash map performance is O(1).
If you do care about string lengths then you need to add another variable to the analysis.
- Let's define n as the number of items in the hash map.
- Let's define k as the length of the string being read/written.
The hash function is O(k) since it loops over the input string in linear time. Therefore, get() and set() are also O(k).
Why don't we care about k normally? Why do people only talk about n? It's because k is a factor when analyzing the hash function's performance, but when we're analyzing how well the hash map performs we don't really care about how quickly the hash function runs. We want to know how well the hash map itself is doing, and none of its code is directly impacted by k. Only hash() is, and hash() is not a part of the hash map, it's merely an input to it.
{}on it's own is considered a HashMap, doesn't it? i'm trying to implement one myself.gettakes when you have one entry and compare that to has long it takes when you have a million entries. One average they will be the same.