效率问题,同样的遍历操作使用EntrySet比用KeySet有明显的效率提升,而增强for循环和用迭代器遍历Set的效率相似。
验证见代码:
Map<String, String> strMap = new HashMap<String, String>();
String tempStr = "";
long ts = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
strMap.put(String.valueOf(i), String.valueOf(i+1));
}
long t0 = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
Iterator<String> ketIter = strMap.keySet().iterator();
while (ketIter.hasNext()) {
tempStr = ketIter.next();
tempStr = strMap.get(tempStr);
}
}
long t1 = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
for(String key : strMap.keySet()) {
tempStr = key;
tempStr = strMap.get(key);
}
}
long t2 = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
Iterator<Entry<String, String>> strMapItor = strMap.entrySet().iterator();
while (strMapItor.hasNext()) {
Entry<String, String> entry = strMapItor.next();
tempStr = entry.getKey();
tempStr = entry.getValue();
}
}
long t3 = System.currentTimeMillis();
System.out.println("Time0--" + (t0 - ts));
System.out.println("Time1--" + (t1 - t0));
System.out.println("Time2--" + (t2 - t1));
System.out.println("Time2--" + (t3 - t2));
结果:
Time0--1320
Time1--3555
Time2--3550
Time2--2753
可见使用EntrySet比KeySet有明显提升,增强for循环和用迭代器遍历Set的效率相似。