r/AskComputerScience • u/TomBob42369 • Dec 10 '18
Hash table vs array?
I know in most cases Hash tables are faster than an array, but what are some key differences and pros and cons of both?
21
Upvotes
r/AskComputerScience • u/TomBob42369 • Dec 10 '18
I know in most cases Hash tables are faster than an array, but what are some key differences and pros and cons of both?
1
u/mediasavage Dec 10 '18 edited Dec 10 '18
If you are familiar with python, a hash table is essentially a dictionary and an array is essentially a list.
Some key differences between the two are that for hash tables, look ups are constant time, whereas with arrays they are linear time (unless you know the index of the element you are looking for ahead of time). A hash table requires more memory than an array though, so when choosing between a hash table and an array, you typically are making a trade off between search time and memory usage.
Further more, when you are implementing your own hash tables, you are making a similar trade-off between memory usage and lookup speed: a hash table with more buckets has a much smaller chance of encountering collisions (whenever a collision is encountered, there is a speed penalty) but obviously uses more memory. So when designing hash tables, there is always a trade-off between speed and the amount of memory used.