对于 HashMap<Integer,Integer>,在插入 10000000 个唯一随机值后。我使用 hashmap 的 keySet() 执行 get(),如下面的代码片段所示:
HashMap<Integer, Integer> hashmap =
new HashMap<Integer, Integer>(10000000, 0.99f);
// ... Code to put unique 10000000 associations into the hashmap ...
int iteration = 100;
long startTime, totalTime = 0;
while(iteration > 0) {
for(Integer key: hashmap.keySet()) {
startTime = System.currentTimeMillis();
hashmap.get(key);
totalTime += (System.currentTimeMillis() - startTime);
}
iteration--;
}
System.out.println(totalTime/100 + " ms");
运行上面的代码,我得到:225 ms
现在,如果我将上面的代码更改为使用集合,例如以下代码段:
Set<Integer> set = new HashSet<Integer>(hashmap.keySet());
while(iteration > 0) {
for(Integer key: set) {
startTime = System.currentTimeMillis();
hashmap.get(key);
totalTime += (System.currentTimeMillis() - startTime);
}
iteration--;
}
System.out.println(totalTime/100 + " ms");
运行此代码后,我得到:414 ms
为什么会有这样的性能差异?
PS:我使用了以下 JVM 参数:
-Xms2048m -Xmx4096m -XX:MaxPermSize=256m