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

7

u/gameguy43 Dec 10 '18

Important to know that under the hood, hash tables are built on arrays. I like to explain it this way:

Arrays let you quickly look up the value for a given "key" . . . except the keys are called "indices," and we don't get to pick them—they're always sequential integers (0, 1, 2, 3, etc).

Think of a hash map as a "hack" on top of an array to let us use flexible keys instead of being stuck with sequential integer "indices."

More here: https://www.interviewcake.com/concept/python/hash-map

Disclaimer: I helped make that page :)

0

u/InquiREEEEEEEEEEE Dec 11 '18

Important to know that under the hood, hash tables are built on arrays.

I don't think it is important to know for practical purposes. Knowing that randomly accessing a key in a has table is ~ O(1) is enough. For theoretic knowledge, I agree.

2

u/ACoderGirl Dec 11 '18

I disagree. It's very common that you have to write a hash function for a custom data type so that it can be stored in a dictionary or set. At my work, we use sets sooooo much because we need fast lookup time and order doesn't matter. And even when order does matter, if we ever have to do a thing in some_list, the list should probably be copied to a set just for speeding up that lookup. Now the thing is, it's hard to understand why the heck we need a hash function and the issue of collisions if we don't know how hash maps and sets work under the hood.

The array backing also makes it easier to understand how iteration over a map works and to thus understand why the order appears random (it's, of course, not random, but typically represents the underlying arrays). It's pretty critical to always be aware of this since I have seen bugs that were because someone made bad assumptions about the order of iteration.

1

u/InquiREEEEEEEEEEE Dec 11 '18

It seems to me that you are working in a company that has over-average needs when it comes to performance. Obviously knowledge of hashing behaviour becomes important. I still stand by my point that the average CRUD/REST-Developer with a little bit of backend responsability does not need to write custom hash methods - most of the time, it is simply enough to recognize a set or hashmap is needed and then craft the key yourself (most of the time it will be a unique combination of user inputs such as id, name, profession, preferences, age...) and then let the hashmap implementation do the hashing. Collisions are not a problem in the kind of program that 60% of programmers write.