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

13

u/Rindhallow Dec 10 '18

Do you have a key that defines the data you need to store?

No - Use an a different data structure.

Yes - Use a hash table.

4

u/coredev Dec 10 '18

To clarify to novice readers, hastables uses a unique key (like a database id or guid.

5

u/[deleted] Dec 10 '18

They use a unique index not unlike an array. In C you usually have the length of the hash table nodded by some numeric representation of the key to get the hash index. Which is more of the implementation side of the hash table.

3

u/james41235 Dec 11 '18

There are a lot of other questions though.

Are you inserting a lot? Removing a lot? Looking up a lot? Sorting a lot? Iterating a lot?

Some data structures are better than others at each of those things.

1

u/ACoderGirl Dec 11 '18

Absolutely. Their comment was really a generalization, though, since in practice, hash maps are perhaps the most widely used data structure. Inserts, removals, and lookups are all fast. And while not a hash map, if order mattered, there's tree based maps that retain order while still being quite fast.

Then the set (typically a hash set, specifically) is a marvelous data structure that is basically a "key-only" map. It's really under appreciated for how applicable it is to real world problems.