第二個選項肯定更有效,因為在第一個選項中只進行一次查找,次數為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毫秒
…等等