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);
		 
	}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM