HashMap,LinkedHashMap,TreeMap读取大量数据效率的比较

	@Test
	public void test() {
		Integer count =1000000;
		Random random =new Random();
		Map map = new HashMap();
		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 linkedMap = new LinkedHashMap();
		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 treeMap = new TreeMap();
		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 map = new HashMap();
		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 linkedMap = new LinkedHashMap();
		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 treeMap = new TreeMap();
		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

你可能感兴趣的:(面试)