插入速度比较HashMap,LinkedHashMap

时间:2015-04-23 07:54:24

标签: performance hashmap linkedhashmap cpu-speed

尝试比较HashMap和LinkedHashMap之间的插入速度我发现最初对于较小的没有对象,直到100000个对象,HashMap的速度更快。 但是,当我将插入计数设置为500000时,速度显然更快 对于LinkedHashMap。 请使用连接的代码验证此方案。 有人可以说明为什么速度比较会逆转。

下面是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());
  }*/

}

}

0 个答案:

没有答案