您的第二个选项肯定更有效率,因为您只在第一个选项中进行了一次查找,而第n次只进行一次查找。
但是,没有什么比坚持下去更好的了。所以这里去 -
(不完美的,但不够好,以验证假设,反正我的机器上)
public static void main(String args[]) {
Map<String, Integer> map = new HashMap<String, Integer>();
// populate map
int mapSize = 500000;
int strLength = 5;
for(int i=0;i<mapSize;i++)
map.put(RandomStringUtils.random(strLength), RandomUtils.nextInt());
long start = System.currentTimeMillis();
// alt. #1
for (String key : map.keySet()) {
Integer value = map.get(key);
// use key and value
}
System.out.println("Alt #1 took "+(System.currentTimeMillis()-start)+" ms");
start = System.currentTimeMillis();
// alt. #2
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
// use key and value
}
System.out.println("Alt #2 took "+(System.currentTimeMillis()-start)+" ms");
}
成绩(一些有趣的)
随着int mapSize = 5000; int strLength = 5;
Alt键#1把26 ms
Alt#2花了20 ms
With int mapSize = 50000; int strLength = 5;
Alt键#1把32毫秒
Alt键#2用了20毫秒
随着int mapSize = 50000; int strLength = 50;
Alt键#1把22毫秒
Alt键#2把21毫秒
随着int mapSize = 50000; int strLength = 500;
Alt键#1把28 MS
Alt键#2花了23毫秒
随着int mapSize = 500000; int strLength = 5;
Alt键#1把92毫秒
Alt键#2把57毫秒
...等等
究竟有多大地图使用它?这听起来像不成熟的优化。 – 2011-04-28 23:55:01
@Matt我问,因为我有几个,他们是巨大的 - 通常是10K-100K元素的调子;绝对有一个优化的好例子! – bguiz 2011-04-28 23:57:36
更新:许多答案似乎认为这是过早的优化。请注意,上述确实是SSCCE(http://sscce.org/),而不是我期待优化的代码的实际位数! – bguiz 2011-04-29 00:19:43