This week's book giveaway is in the Java in General forum.
We're giving away four copies of Event Streams in Action and have Alexander Dean & Valentin Crettaz on-line!
See this thread for details.
Win a copy of Event Streams in Action this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

performance of different keys in map

Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a question on java.util.Map performance.
does the key I use affect the performance of a map. i.e. would a map keyed on an integer key have the same performance as one keyed on a say a 64 character string ?
If so, in what operations would the performance differ.
Any help greatly appreciated,
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It all depends on the objects implementation of hashCode(). Integers should be very effecient. Strings probably less so.
For a hash table to work, they hashcode has to be calculated for the object each time you put the object in, or get the object from the hashtable. Luckily it is only calculated once each time and it usually isn't a performance concern.
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alternately, if you're using a TreeMap, then it's the compareTo() method that's used, rather than hashCode(). The same comments apply though, with minor differences. It's when you put() and get() that the compareTo method is invoked, repeatedly (long n times). And just like for a HashMap, an int key will almost certainly have a faster compareTo() than a String does.
A HashMap will also use the equals() method, in addition to hashCode(). This may be invoked multiple times, or not at all, during a get() or put() - depending on the distribution of keys already in the Map.
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!