使用两个类似的代码块在HashMap中查找键的运行时存在显著差异



我使用HashMap.containsKey检查HashMap中是否存在密钥,并在下面的代码中计算了持续时间:

public static void main(String[] args){
long startTime = System.nanoTime();
HashMap<String,Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
if(map.containsKey("four")){
System.out.println("true");
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println(duration);
}

持续时间为:48278

我使用HashMap.containsKey来检查HashMap中是否不存在密钥,并在下面的代码中计算了持续时间:

public static void main(String[] args){
long startTime = System.nanoTime();
HashMap<String,Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
if(!(map.containsKey("four"))){
System.out.println("true");
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println(duration);
}

持续时间为:378741

所以在第一个代码中;四";,在第二个代码中,我检查地图中是否不存在钥匙(检查第七行(。为什么第二个运行时间如此之长?他们基本上不是在做同样的事情吗?

在您的示例中,这种差异是由使用System.out.println((引起的。这需要时间,应该是造成这种差异的主要原因。

不管怎样,你的测量方法不好。执行时间可能因时间而异。这是由于许多因素造成的,例如JVM的JIT或CPU的CacheMisses。如果你只测量一次执行时间,结果是不准确的。如果您执行代码数十万次,这些不一致加起来为零。

最新更新