给定以下代码,有两种替代方法可以遍历它,
这两种方法在性能上有区别吗?
Map<String, Integer> map = new HashMap<String, Integer>();
//populate map
//alt. #1
for (String key : map.keySet())
{
Integer value = map.get(key);
//use key and value
}
//alt. #2
for (Map.Entry<String, Integer> entry : map.entrySet())
{
String key = entry.getKey();
Integer value = entry.getValue();
//use key and value
}
我倾向于认为 alt. #2
是遍历整个 map
的更有效方法(但我可能错了)
最佳答案
您的第二个选项肯定更有效,因为与第一个选项中的 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 毫秒
Alt #2 耗时 20 毫秒
使用 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 毫秒
Alt #2 耗时 23 毫秒
使用 int mapSize = 500000; int strLength = 5;
Alt #1 耗时 92 毫秒
Alt #2 耗时 57 毫秒
...等等
关于Java : Iteration through a HashMap, 哪个效率更高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5826384/