Hashtables and HashMaps
Because
Hashtable
s and
HashMap
s are the most commonly used nonlist
structures, I will spend a little extra time discussing them.
Hashtable
s and HashMap
s are
pretty fast and provide adequate performance for most purposes. I
rarely find that I have a performance problem using
Hashtable
s or HashMap
s, but
here are some points that will help you tune them, or, if necessary,
replace them:
Hashtable
issynchronized
. 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.Hashtable
s andHashMap
s 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 theloadFactor
(the default load factor is 0.75).Hashtable
s andHashMap
s are faster with a smallerloadFactor
, 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.