I've been hearing everybody championing HashMaps over Hashtables
becuause they're unsynchronized, therefor much faster for quite some
time. I tried to benchmark the two and I got results which are puzzling.
The test does not try to measure the performance directly, instead it
compares the two. The test has lots of other stuff going on but that
stuff should be identical for each.
Here's my test code
import java.util.*;
public class t
{
static final int ITER = 500000;
static void doHash (Map t)
{
for (int i=0; i<ITER; ++i)
{
Integer in = new Integer(i);
t.put(in, in);
}
for (int i=0; i<ITER; ++i)
{
Integer in = new Integer(i);
Object o = t.get(in);
if (!(o instanceof Integer)) // Do something with the result
System.out.println(i+" wasn't an Integer");
}
}
public static void main (String[] argv)
{
// Warm up hotspot
for (int i=0; i<3; ++i)
{
doHash(new Hashtable());
doHash(new HashMap());
}
// Time the calls
for (int i=0; i<10; ++i)
{
Map t = new Hashtable();
long start = System.currentTimeMillis();
doHash(t);
System.out.println("Hashtable
"+(System.currentTimeMillis()-start));
t = new HashMap();
start = System.currentTimeMillis();
doHash(t);
System.out.println("HashMap
"+(System.currentTimeMillis()-start));
}
}
}
I ran my test with -server, as it gave better times (as expected)
java -server -cp . t
On Red Hat Fedora, running an PIII, 700MHz 512MByte ram
java version "1.4.2_03"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_03-b02)
Java HotSpot(TM) Client VM (build 1.4.2_03-b02, mixed mode)
Hashtable 2461
HashMap 4104
Hashtable 2502
HashMap 4609
Hashtable 3174
HashMap 4062
Hashtable 2788
HashMap 5572
Hashtable 2516
HashMap 4094
Hashtable 2471
HashMap 4094
Hashtable 2482
HashMap 4026
Hashtable 2444
HashMap 4091
Hashtable 2460
HashMap 4063
Hashtable 2480
HashMap 4081
On Mac OSX 10.3, on a G3 450MHz 768MByte ram
java version "1.4.1_01"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_01-99)
Java HotSpot(TM) Client VM (build 1.4.1_01-27, mixed mode)
Hashtable 4361
HashMap 5705
Hashtable 4366
HashMap 5640
Hashtable 4188
HashMap 5807
Hashtable 4313
HashMap 5793
Hashtable 4054
HashMap 5648
Hashtable 4197
HashMap 5749
Hashtable 4428
HashMap 5692
Hashtable 4110
HashMap 5955
Hashtable 4282
HashMap 5552
Hashtable 4216
HashMap 5776
On W2K on 1 PIII 1000MHz, 1GByte ram
java version "1.4.2_01"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_01-b06)
Java HotSpot(TM) Client VM (build 1.4.2_01-b06, mixed mode)
Hashtable 1502
HashMap 2945
Hashtable 1462
HashMap 2954
Hashtable 1492
HashMap 2855
Hashtable 1392
HashMap 2954
Hashtable 1462
HashMap 2944
Hashtable 1452
HashMap 2934
Hashtable 1472
HashMap 2954
Hashtable 1503
HashMap 3134
Hashtable 1422
HashMap 3005
Hashtable 1432
HashMap 2994
It looks like the Hashtable is considerably faster than the Hashmap