网上看了很多博客,关于hashMap和LinkHashMap的区别时候,基本上都说的是HashMap查询速度快,LinkedHashMap的查询速度慢,我自己测试了一下,代码如下:
结果不管我设置一次插入数值多少,写入的速度和读取的速度,都是LinkedHashMap吊打hashMap,有大佬来解释一下原因么?
public static void insertHashMapTest() throws InterruptedException {
int size=50000;
HashMap<String, Double> hashMap = new HashMap<>(size);
System.out.println("----开始测试hashMap---");
long hashMapStart = System.currentTimeMillis();
for(int i=0;i<size;i++){
hashMap.put(UUID.randomUUID().toString(),Math.random());
}
System.out.println("hashMap插入"+size+"条数据消耗时间为:"+(System.currentTimeMillis()-hashMapStart));
long hashMapcheck = System.currentTimeMillis();
Iterator<Map.Entry<String, Double>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()){
System.out.print(iterator.next().getValue());
}
System.out.println("##");
System.out.println("hashMap遍历"+size+"条数据消耗时间为:"+(System.currentTimeMillis()-hashMapcheck));
//清空hashMap,避免影响内存
hashMap.clear();
//清除hashmap需要时间,此过程会影响linkedhashmap的速度,确保hashmap清理完毕再执行
Thread.sleep(3000);
System.out.println("hashMap长度:"+hashMap.size());
System.out.println("----开始测试linkHashMap---");
LinkedHashMap<String, Double> linkedHashMap = new LinkedHashMap<>(size);
long linkHashMapStart = System.currentTimeMillis();
for(int i=0;i<size;i++){
linkedHashMap.put(UUID.randomUUID().toString(),Math.random());
}
System.out.println("linkHashMap插入"+size+"条数据消耗时间为:"+(System.currentTimeMillis()-linkHashMapStart));
long linkHashMapcheck = System.currentTimeMillis();
Iterator<Map.Entry<String, Double>> iterator1 = linkedHashMap.entrySet().iterator();
while (iterator1.hasNext()){
System.out.print(iterator1.next().getValue());
}
System.out.println("##");
System.out.println("linkHashMap遍历"+size+"条数据消耗时间为:"+(System.currentTimeMillis()-linkHashMapcheck));
}