HashMap,LinkedHashMap,TreeMap讀取大量資料效率的比較

擊水三千里發表於2019-03-15
	@Test
	public void test() {
		Integer count =1000000;
		Random random =new Random();
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < count; i++) {
			map.put(i+"", i+"");
		}
		long time1 = System.currentTimeMillis();
		for (int i = 0; i < count; i++) {
			map.get((random.nextInt(count)+1)+"");
		}
		long time2 = System.currentTimeMillis();
		System.out.println("HashMap time:" + (time2 - time1));
		////////////////////////////////////////////////////////////////////////
		Map<String, String> linkedMap = new LinkedHashMap<String, String>();
		for (int i = 0; i < count; i++) {
			linkedMap.put(i+"", i+"");
		}
 
		time1 = System.currentTimeMillis();
		for (int i = 0; i < count; i++) {
			 linkedMap.get((random.nextInt(count)+1)+"");
		}
		time2 = System.currentTimeMillis();
		System.out.println("LinkedHashMap time:" + (time2 - time1));
                ////////////////////////////////////////////////////////////////////////
		Map<String, String> treeMap = new TreeMap<String, String>();
		for (int i = 0; i < count; i++) {
			treeMap.put(i+"", i+"");
		}

		time1 = System.currentTimeMillis();
		for (int i = 0; i < count; i++) {
			treeMap.get((random.nextInt(count)+1)+"");
		}
		time2 = System.currentTimeMillis();
		System.out.println("TreeMap time:" +  (time2 - time1));
	}

上述程式碼的執行結果: 

HashMap time:641
LinkedHashMap time:703
TreeMap time:4040

 如果讀取資料是有序的呢

	@Test
	public void test2() {
		Integer count =1000000;
		Random random =new Random();
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < count; i++) {
			map.put(i+"", i+"");
		}
		long time1 = System.currentTimeMillis();
		for (int i = 0; i < count; i++) {
			map.get(i+"");
		}
		long time2 = System.currentTimeMillis();
		System.out.println("HashMap time:" + (time2 - time1));
		////////////////////////////////////////////////////////////////////////
		Map<String, String> linkedMap = new LinkedHashMap<String, String>();
		for (int i = 0; i < count; i++) {
			linkedMap.put(i+"", i+"");
		}
 
		time1 = System.currentTimeMillis();
		for (int i = 0; i < count; i++) {
			 linkedMap.get(i+"");
		}
		time2 = System.currentTimeMillis();
		System.out.println("LinkedHashMap time:" + (time2 - time1));
        ////////////////////////////////////////////////////////////////////////
		Map<String, String> treeMap = new TreeMap<String, String>();
		for (int i = 0; i < count; i++) {
			treeMap.put(i+"", i+"");
		}

		time1 = System.currentTimeMillis();
		for (int i = 0; i < count; i++) {
			treeMap.get(i+"");
		}
		time2 = System.currentTimeMillis();
		System.out.println("TreeMap time:" +  (time2 - time1));
	}

HashMap time:297
LinkedHashMap time:203
TreeMap time:438

 

總結:

讀取大量資料的前提下

1、key是隨機的情況下獲取map的value時的效能表現 HashMap>LinkedHashMap>TreeMap

2、key是有序的情況下獲取map的value時的效能表現 LinkedHashMap>HashMap>TreeMap

相關文章