Search code examples
javahashtable

Which is faster, String or Integer as hashkey in Java?


I am working on a problem and I have problem with execution times becoming too large and now Im looking for possible optimizations.

The question: Is there any (considerable) difference in performance between using String or Integer as haskey?

The problem is I have a graph with nodes stored in a hashtable with String as key. For example the keys are as follows - "0011" or "1011" etc. Now I could convert these to integers aswell if this would mean a improvement in execution time.


Solution

  • If you have performance problem, it's quite unlikely that the issue is due to the HashMap/HashTable. While hashing string is slightly more expensive than hashing integers, it's rather small difference, and hashCode is cached so it's not recalculated if you use the same string object, you are unlikely to get any significant performance benefit from converting it first to integer.

    It's probably more fruitful to look somewhere else for the source of your performance issue. Have you tried profiling your code yet?