第二个选项肯定更有效,因为在第一个选项中只进行一次查找,次数为n次。
但是,没有什么比尝试它更好,当你可以。所以这里 –
(不完美,但足够好验证假设和我的机器)
public static void main(String args[]) {
Map map = new HashMap();
// populate map
int mapSize = 500000;
int strLength = 5;
for(int i=0;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 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花费了26ms
Alt#2花了20毫秒
使用int mapSize = 50000; int strLength = 5;
Alt#1花了32 ms
Alt#2花了20毫秒
使用int mapSize = 50000; int strLength = 50;
Alt#1花了22毫秒
Alt#2花费了21ms
使用int mapSize = 50000; int strLength = 500;
Alt#1花费了28ms
Alt#2花了23毫秒
使用int mapSize = 500000; int strLength = 5;
Alt#1花了92毫秒
Alt#2花了57毫秒
…等等