1

Map (or HashMap) takes Constant time for Insert, Remove and Retrieve. While all other data structures which I know so far, do not take constant time and their time for above operations depends on the size of input.

So, why do we need all other data structures ever ? Isn't HashMap is universal data structure ?

SimpleGuy
  • 121

2 Answers2

7
  1. Hash map has constant time for most operations - on average. Worst case complexity is much higher. A list or a tree can guarantee fast (even if not constant) time in every case (even for maliciously crafted input).
  2. Element lookup in an array is usually a single CPU instruction. Hash map adds a lot overhead over that - even if both have constant average complexity.
  3. It doesn't keep any order of elements. Inserting elements at particular position requires rebuilding whole hash map. Iterating over elements in particular order requires converting to a different data structure.
  4. Hash map has much higher memory footprint than tightly packed array or carefully designed linked list. It usually has much worse cache locality.
  5. Not all data types are easily hashable.
Banthar
  • 350
2

For example, array and hashmap both have constant access time (on average). However, for an array the constant is much, much smaller. And for an array, the memory usage is much smaller, because a hash map would store the indices as well, and have many unused slots (because hashing gets slow of the percentage of used slots gets too high).

And then there are vector instructions. A modern Intel processor can read 8 float values or 32 byte values from an array in a single instruction. Those 32 byte values would have to go through the (constant time but slow) hashing code 32 times. I'd say that would easily give you a factor 1000 for total slowdown.

gnasher729
  • 49,096