Map和EntrySet、keySet的迭代效率


虚拟机环境:

操作系统:win7

平台:eclipse 3.7

 实验目的:对比Map和EntrySet、keySet的迭代效率,从而对比得出map效率较高的迭代方式。

实现方式:通过迭代相同的map,分别记录迭代的开始和结束时间,对比两种迭代的总耗时,得出结论。

实验结果: 10000次测试中keySet用时2999次大于entry用时

10000次测试中entry用时2323次大于keySet用时

10000次测试中用时相等4678次

实验结果:entrySet 迭代效率更高

实验代码:

public class Apple {
	private String name;
	private String id;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
}

public class Test {
	public static void main(String[] args) {
		Map<String, Apple> map = new HashMap<String, Apple>();
		Random random = new Random();
		int resultBig = 0;
		int resultEqul = 0;
		int total = 10000; 
		for (int round = 0; round < total; round++) {
			int rand = random.nextInt(90000);
			for (int i = 0; i < rand; i++) {
				map.put("data" + i, new Apple());
			}

			long sumTime1 = 0;// keySet方法用时
			long sumTime2 = 0;// entry方法用时
			long startTime1 = 0;// keySet方法开始时间
			long startTime2 = 0;// entry方法开始时间

			Iterator<String> keys = map.keySet().iterator();
			startTime1 = System.currentTimeMillis();
			while (keys.hasNext()) {
				String key = (String) keys.next();
				Apple val = map.get(key);
				// System.out.println(key + " : " + val);
			}
			sumTime1 = System.currentTimeMillis() - startTime1;
			System.out.println("keySet: " + sumTime1);

			Iterator<Entry<String, Apple>> iter = map.entrySet().iterator();
			startTime2 = System.currentTimeMillis();
			while (iter.hasNext()) {
				Entry<String, Apple> entry = iter.next();
				String a = entry.getKey();
				Apple b = entry.getValue();
				// System.out.println(a + " : " + b);
			}
			sumTime2 = System.currentTimeMillis() - startTime2;
			System.out.println("entry: " + sumTime2);
			
			System.out.println("----------------"+ "map数据量: " + rand + "------------------------");	
			
			if(sumTime1 > sumTime2){
				resultBig++;
			}else if(sumTime1 == sumTime2){
				resultEqul++;
			}
		}
		System.out.println(total + "次测试中" + "keySet用时" + resultBig + "次大于entry用时");
		System.out.println(total + "次测试中" + "entry用时" + (total-resultBig-resultEqul) + "次大于keySet用时");
		System.out.println(total + "次测试中" + "用时相等" + resultEqul + "次");
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值