1

I wrote a standalone program, trying to put 10k elements in a hasmap and hashtable; here I observed hashtable is faster than hashmap for insertion.

HashMap: (Taken time: 31ms)

public static void main(String[] args) {
    long s = System.currentTimeMillis();
    Map<String, Integer> map = new HashMap<String, Integer>();
    for (int i = 0; i < 10000; i++) {
        map.put("i_" + i, i);
    }
    System.out.println("Taken time: " + (System.currentTimeMillis() - s));
}

HashTable: (Taken time: 15ms)

public static void main(String[] args) {
    long s = System.currentTimeMillis();
    Map<String, Integer> map = new Hashtable<String, Integer>();
    for (int i = 0; i < 10000; i++) {
        map.put("i_" + i, i);
    }
    System.out.println("Taken time: " + (System.currentTimeMillis() - s));
}

Is that understanding correct?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Ram Kowsu
  • 711
  • 2
  • 10
  • 30
  • 5
    *"Is that understanding correct?"* - This does not ring true. I suspect that you have made a mistake in the way you are benchmarking. – Stephen C Jan 22 '20 at 04:40
  • 9
    Read [How do I write a correct micro-benchmark in Java](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java) – Stephen C Jan 22 '20 at 04:41
  • 8
    Please read [Differences between HashMap and Hashtable](https://stackoverflow.com/questions/40471/differences-between-hashmap-and-hashtable). Hashtable is obsolete now, but in any case your benchmark may not be that meaningful because it is just one point of data, and who knows what else might be going on in the background JVM. Actually, Hashtable is synchronized, so I would in general expect HashMap to outperform it. – Tim Biegeleisen Jan 22 '20 at 04:42
  • @TimBiegeleisen The compiler with standard settings should be smart enough to see that no synchronization is needed in this example. Other than that I agree with you. – Ole V.V. Jan 22 '20 at 05:43
  • @OleV.V. I was more generally referring the OP's benchmark, which may be flawed because of background things like JVM startup time. – Tim Biegeleisen Jan 22 '20 at 05:44
  • @TimBiegeleisen, You are correct. When I add both (hashmap & hashtable) put statements in separate methods; i.e, first i call the method hashtable put then hashmap put method. now I can see the clear diff. Thank you :) – Ram Kowsu Jan 22 '20 at 06:28

1 Answers1

0

Sorry no hashmap is faster. HashMap and Hashtable are vritually identical except that Hashtable is synchronized. This causes Hashtable to perform slower than Hashmap.

PROOF https://coderanch.com/t/202040/java/Hashtable-HashMap