首页 > 代码库 > 用for和while遍历HashMap效率测试

用for和while遍历HashMap效率测试

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

public class EntryTest {
	public static void main(String[]  args) {
		
		Map<Integer, String> map = new HashMap<Integer, String>();
		for (int i = 0; i <= 6000000; i++) {
			map.put(i, "a" + i);
		}
		
		//使用while和entrySet遍历HashMap
		long startTime1 = Calendar.getInstance().getTimeInMillis();		
		Iterator iterator = map.entrySet().iterator();
		while(iterator.hasNext()) {
			Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>)iterator.next();
			entry.getKey();
			entry.getValue();
			//System.out.println(entry.getKey() + ": " + entry.getValue());
		}
		long endTime1 = Calendar.getInstance().getTimeInMillis();
		
		//输出方法1的耗时
		System.out.println("costTime1 = " + (endTime1-startTime1));
		
		//使用for和entrySet遍历
		long startTime2 = Calendar.getInstance().getTimeInMillis();
		for (Map.Entry<Integer, String> entry:map.entrySet()) {
			entry.getKey();
			entry.getValue();
			//System.out.println(entry.getKey() + ": " + entry.getValue());
		}
		long endTime2 = Calendar.getInstance().getTimeInMillis();
		
		//输出方法2的耗时
		System.out.println("costTime2 = " + (endTime2-startTime2));		
	}
	
}
结果输出:
costTime1 = 96costTime2 = 89