HomeSearch

Java Hashtable Usage and Performance

This Java article uses the Hashtable collection from java.util.Hashtable. It benchmarks Hashtable and HashMap.
Hashtable. This is an associative array: it associates keys (of any type) to values (of any type). HashMap is similar to Hashtable but not thread safe. It is slower.
Not preferred. With Hashtable, performance is reduced by internal synchronization (thread-checking) code. This makes it about 200% slower than HashMap on simple lookups (with containsKey).
Sample usage. This program shows how to create a new Hashtable with String keys, Integer values. We can use any class type for the keys and values. We use put and get.

Put: This assigns a new entry in the Hashtable. The key is the first argument. The value is the second.

Get: This looks up a value in the Hashtable from the key. Internally it computes a hash code from the key for faster searching.

Java program that uses Hashtable import java.util.Hashtable; public class Program { public static void main(String[] args) { // Create Hashtable and add two entries. Hashtable<String, Integer> hash = new Hashtable<>(); hash.put("cat", 10); hash.put("dog", 15); // Get value at this key. int value = hash.get("cat"); System.out.println(value); } } Output 10
A benchmark. This program benchmarks the Hashtable against HashMap. The HashMap is faster, for simple lookups, by about 200%. Using HashMap when possible is a clear win.
Java program that benchmarks Hashtable, HashMap import java.util.HashMap; import java.util.Hashtable; public class Program { public static void main(String[] args) throws Exception { Hashtable<String, Integer> table = new Hashtable<>(); table.put("carrot", 10); table.put("apple", 20); HashMap<String, Integer> map = new HashMap<>(); map.put("carrot", 10); map.put("apple", 20); long t1 = System.currentTimeMillis(); // ... Check Hashtable. for (int i = 0; i < 1000000; i++) { if (!table.containsKey("apple")) { throw new Exception(); } } long t2 = System.currentTimeMillis(); // ... Check HashMap. for (int i = 0; i < 1000000; i++) { if (!map.containsKey("apple")) { throw new Exception(); } } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 53 17
In most programs, a HashMap is the better choice. If we have complex threading requirements, Hashtable may be necessary. HashMap has a significant performance advantage.
Retrofitted. Over the years, Hashtable has been retrofitted to support modern interfaces and generics in Java. And HashMap was introduced to provide an entirely new, faster option.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls