hi, 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, thanks, Tom
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.
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.