2

Trying to compare the speed of insertion between a HashMap and a LinkedHashMap I found that initially for a smaller no of objects until 100000 objects the speed was faster for the HashMap. However when I set the insertion count to 500000 the speed was clearly faster for the LinkedHashMap. Please use the code connected to verify this scenario. Could someone throw light on why the speed comparision gets reversed.

below is Class HashMapTest:

import java.util.HashMap;
import java.util.LinkedHashMap;

public class HashMapTest {

public static void main(String args[]) {

  final int count = 100000;
   // Create a hash map
  HashMap<String, Comparable> hm = new HashMap();
  LinkedHashMap<String, Comparable> lhm = new LinkedHashMap();

  // Put elements to the map
   long startTime = System.nanoTime();    

  for (int i = 0; i < count; i++){
      hm.put("Obj" + i, new String("" + i));
  }   
   long estimatedTime = System.nanoTime() - startTime;
  System.out.println("\n Time Taken To Insert " + count + " objects (HashMap)= " + estimatedTime / 1000000 + " MilliSeconds" ); 

  startTime = System.nanoTime();    

for (int i = 0; i < count; i++){
    lhm.put("Obj" + i, new String("" + i));
}     

  long estimatedTimeLinked = System.nanoTime() - startTime;

  System.out.println("\n Time Taken To Insert " + count + " objects (LinkedHashMap)= " + estimatedTimeLinked / 1000000 + " MilliSeconds" );

  System.out.println("\n Difference between Linked and Normal " + (estimatedTimeLinked - estimatedTime) / 1000000 + " MilliSeconds" );
    /*  Set set = hm.entrySet();
  Iterator i = set.iterator();

  // Display elements
  while(i.hasNext()) {
     Map.Entry me = (Map.Entry)i.next();
    // System.out.print(me.getKey() + ": ");
   //  System.out.println(me.getValue());
  }*/

}

}

Bhargav Modi
  • 2,605
  • 3
  • 29
  • 49
acearch
  • 343
  • 1
  • 8

0 Answers0