OrangeMan
OrangeMan

Reputation: 692

Faster to retrieve objects via hashmap or iterate over array?

Basically i have an enum with an id.

Would it be faster to create a hashmap that would take the id and give you the enum or iterate over all the enums testing if the id provided is equal to the id of the enum, and if so returning it.

If it matters then there are 5 enums.

Upvotes: 2

Views: 2821

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533442

If you have an Enum as a key, you should use an EnumMap. This basically wraps an array of values and is faster than using a HashMap.

Upvotes: 1

Michael Piefel
Michael Piefel

Reputation: 19968

A hashmap has a lookup complexity of O(1), while iterating naturally has O(n). That said, for only 5 enum values the iteration will probably be faster on average, and it will not need an extra data structure when you just iterate over .values() anyway.

Upvotes: 2

NickJ
NickJ

Reputation: 9559

HashMaps are specifically designed for retrieving objects via a key, and are fast even with many entries. Usually, a sequential scan of a list or similar collection would be much slower.

But if you have only 5 items, there's no real difference.

Edit: on second thoughts, with so few objects you might be better off with a sequential scan because the extra work in calculating the hash codes might outweigh the advantage. But the difference is so small it's not worth bothering about.

Upvotes: 8

Related Questions