HashMap随机取值和迭代器取值的对比

一共四中方法,前两种是迭代器取值,后两种是随机取值,循环了5000万次,时间分别为:迭代器读取的速度大约是随机读取的速度的1.5倍,数据量越大,差距越明显。

另外,插入是读取的100倍左右的时间(这个判定只是个大概参考)。

48138(插入)

403(迭代器读取)

400(迭代器读取)

653(随机读取)

561(随机读取)

package main;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class test {
	public static void main(String[] args) {
		 int mapCount = 50000000;
		 String tmp = "";
		 
		 Map<Integer,String> testMap = new HashMap<>();
		 String testValue = "";
		 Long startTime0 = System.currentTimeMillis();
		 for(int i = 1;i<mapCount;i++){
			 tmp = testMap.put(i, testValue);
		 }
		 Long endTime0 = System.currentTimeMillis();
		 System.out.println(endTime0-startTime0);
		 
		 Long startTime1 = System.currentTimeMillis();
		 for(Entry<Integer,String> entry : testMap.entrySet()){
			 tmp = entry.getValue();
		 }
		 Long endTime1 = System.currentTimeMillis();
		 System.out.println(endTime1-startTime1);
		 
		 Long startTime2 = System.currentTimeMillis();
		 Iterator<Entry<Integer, String>> it = testMap.entrySet().iterator();
		 while(it.hasNext()){
			 tmp = it.next().getValue();
		 }
		 Long endTime2 = System.currentTimeMillis();
		 System.out.println(endTime2-startTime2);
		 
		 Long startTime3 = System.currentTimeMillis();
		 for(Integer i : testMap.keySet()){
			 tmp = testMap.get(i);
		 }
		 Long endTime3 = System.currentTimeMillis();
		 System.out.println(endTime3-startTime3);
		 
		 Long startTime4 = System.currentTimeMillis();
		 for(Entry<Integer,String> entry : testMap.entrySet()){
			 tmp = testMap.get(entry.getKey());
		 }
		 Long endTime4 = System.currentTimeMillis();
		 System.out.println(endTime4-startTime4);
		 
	}
}

  

posted @ 2017-06-30 21:20  lakeslove  阅读(2893)  评论(0编辑  收藏  举报