Reputation: 6979
I was looking for a best way to loop through a map that involve as minimum resources as possible. Assume I have an object as the value, and the key is a string that referencing to the object. With the following two loop, may I know which one is better and how did you justified it run only minimum resources?
for(Map.Entry<String, MyObject> entry : myMap.entrySet()) {
...
}
for( String key : myMap.keySet() ) {
...
}
THanks @!
Upvotes: 0
Views: 175
Reputation: 7447
For the usual/sensible implementations:
Upvotes: 2
Reputation: 72294
Why are you worried about resources? Is this honestly a practical, legitimate concern or is it a case of premature optimisation?
From a design point of view, I'd use the entryset if you need to deal with the keys and values rather than just the keys. Not from a performance perspective, but from a practical, design perspective it's clearer that you're doing something with the entries in the map if you use that rather than just the keys. (Of course, if you are just doing something with the keys use the keyset.)
As others have mentioned from a performance perspective it's impossible to tell without knowing implementation details, but unless you're doing something very specific or dealing with massive maps, that shouldn't be an issue.
Upvotes: 1
Reputation: 32949
I believe the following is more efficient:
for(Map.Entry<String, MyObject> entry : myMap.entrySet()) {
...
}
This is because it is probably doing a simple iteration over a collection depending on the Map implementation. On the other hand, if you iterate over the key and then call the Map's get method using the key, you are not only iterating over a collection of keys but also doing a lookup to retrieve each element from the Map.
Upvotes: 4
Reputation: 420991
This depends on which specific Map
you use. It's impossible to tell as it stands, since Map
is an interface.
In most map implementations both entrySet
and keySet
will return a view of the underlying set of entries / keys, so I'd say that they are likely more or less as efficient in all aspects.
Note that if you retrieve all entries you're getting the values at the same time. This may save you some time if you often need the value.
Upvotes: 5
Reputation: 52448
What resources do you mean? Memory?
In both cases you have one object reference beng used in the loop - whether it is entry or key. In neither case are other objects created. Both would be more or less equal in performance and resource usage.
Upvotes: 1