虚拟机环境:
操作系统: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 + "次");
}
}