• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Fastest way to iterate through a map

 
Tymur Porkuyan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which of these variants is faster?
Or there is some other faster way?



 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Tymur Porkuyan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic