Reputation: 24084
I need to find objects by an attribute.
One option is to iterate over an array of objects and check for each object that the attribute matches.
The other option is to put the objects in a hashmap, with the attribute as key. Then one can simply retrieve the object by the attribute.
Is the second option good practice, despite the fact that you duplicate the attribute data?
Note: the attribute is assumed to be unique
Upvotes: 3
Views: 346
Reputation: 160171
If the attribute is unique, and there's a lot of objects to search over, or you need to search over them a lot, sure--create an index. That's often the tradeoff--memory over speed.
OTOH, if there aren't a lot of objects, or you don't do it a lot, it may not matter either way.
Upvotes: 1
Reputation: 32949
YES! From what you have given, it would generally always be better to use a Map. Finding a value in a Map (where the key has a good hash function) is O(1). Finding an element in an array or list is O(n).
Upvotes: 6