A hash map that maps keys of type $K$ into values of type $V$, is essentially equivalent to "extending" this type $K$ to also contain an Option<V>
field.
Implementing this in practice (apart from the bad habits of adding more fields that are irrelevant most of the time), shouldn't the "extension" of $K$ be faster in practice and more memory-friendly? Since hash maps take extra redundant space, and aren't guaranteed to work in $O(1)$ worst case deterministically (i.e, not on average) - shouldn't this be the case?
Then how come hash-maps are used so much in practice? What am I missing here?
For more context, since it seems I wasn't clear enough in the question - I will provide the full scenario I'm dealing with, where both approaches work.
Lets say I have some collection Col
of keys with type K
. Our running example will be Col:=Graph
and K:=Node
.
Now, we want run some function on the graph - maybe, BFS. Notice that while running, the BFS algorithm associates with each node the boolean label - "was this node explored already".
Now, my question deals with the specific implementation of how we associate this label to the nodes.
We could use a hash-map, mapping between the nodes and the labels. But we could also explicitly add this label as an extra field to the Node
struct (or class).
So my question is - what are the benefits of each approach? What would be the "better" solution in this case?
Option<V>
field of $k$ is non-empty? This would be $O(1)$ in worst case (and not even amortized or on average) $\endgroup$