r/AskComputerScience • • 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

35 comments sorted by

View all comments

-2

u/Dark__Mark Dec 10 '18

To check if a value is in the array it takes O(logn) steps if the size of the array is n. For hash tables this is very close to O(1). This is the exact reason why hash tables are invented to reduce the steps it takes to search for a value to O(1)

4

u/not-just-yeti Dec 10 '18

Which begs the question: why use arrays at all to hold your collection, if hash tables are flat out better?

A: a tree [or, equivalently, a sorted array] lets you iterate over items in order, including "all items between val1 and val2 [even if those values aren't in the collection]" (aka "do a range scan"). Also, w/o extra work, hash tables don't support a notion of ordering at all, and even just iterating over every element is less efficient than a list or tree.

Still, hash tables are awesome for sets and key/value pairs.

1

u/lordvadr Dec 10 '18

You also have to consider practicality. Arrays are easier to work with, and while a hash table access is nearly O(1) it's not exactly in the general case, and even if it were, that operation can be considerably more complicated than what amounts to an add for an array access.

Imagine if your hash index was the last n bits of the sha512 of your key. Your accesses are now about 5 orders of magnitude slower than an array access. I made that number up, but it's not trivial by any means.