wood burning stoves 2.0*
The moose likes Java in General and the fly likes Fastest way to iterate through a map Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Fastest way to iterate through a map" Watch "Fastest way to iterate through a map" New topic
Author

Fastest way to iterate through a map

Tymur Porkuyan
Greenhorn

Joined: Dec 12, 2005
Posts: 7
Which of these variants is faster?
Or there is some other faster way?



Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

There are many variables involved, and the honest answer is that there's no one answer. It depends on what kind of Map we're talking about, and it depends on how many entries are in the Map. For a TreeMap, looking something up in the Map takes time proportional to the size of the Map; for a HashMap, it's a constant. For some implementations, creating the EntrySet might be expensive (in theory at least,) while for others, creating the keySet() might be.

But in general, iterating over the Map.Entry objects is intended to be more performant.

Note, finally, that worrying about this kind of detail is usually counterproductive until you have a working application and profile data that tells you that iterating over this Map is taking too much time.


[Jess in Action][AskingGoodQuestions]
Tymur Porkuyan
Greenhorn

Joined: Dec 12, 2005
Posts: 7
Thanks!
 
wood burning stoves
 
subject: Fastest way to iterate through a map