Hashtables and HashMaps

Because Hashtables and HashMaps are the most commonly used nonlist structures, I will spend a little extra time discussing them. Hashtables and HashMaps are pretty fast and provide adequate performance for most purposes. I rarely find that I have a performance problem using Hashtables or HashMaps, but here are some points that will help you tune them, or, if necessary, replace them:

  • Hashtable is synchronized. That’s fine if you are using it to share data across threads, but if you are using it single-threaded, you can replace it with an unsynchronized version to get a small boost in performance. HashMap is an unsynchronized version available from JDK 1.2.

  • Hashtables and HashMaps are resized whenever the number of elements reaches the [capacity * loadFactor]. This requires reassigning every element to a new array using the rehashed values. This is not simply an array copy; every element needs to have its internal table position recalculated using the new table size for the hash function. You are usually better off setting an initial capacity that handles all the elements you want to add. This initial capacity should be the number of elements divided by the loadFactor (the default load factor is 0.75).

  • Hashtables and HashMaps are faster with a smaller loadFactor, but take up more space. You have to decide how this tradeoff works best for you.

  • The hashing function should work better with a capacity that is a prime number. Failing this, always use an odd ...

Get Java Performance Tuning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.