2013-11-22 48 views
0

我得到不同的执行时间,如果我交换HashMap和HashSet。首先出现的执行时间总是很高(HashMap/Hashset)。我不确定背后的原因。任何帮助表示赞赏根据执行顺序对HashMap和HashSet执行不同的执行时间?

执行1 - HashMap的第一个,然后HashSet的--- 所用时间地图地址:2071ms, 时间拍摄的这组加载:794ms

执行2 - HashSet的第一,然后HashMap的--- 时间采取集中添加:2147ms, 所用时间地图地址:781ms

private static Random secureRandom = new SecureRandom(); 

public static void main(String args[]) 
{ 

    int testnumber = 1000000; 

    // HashMap 
    long starttimemap = System.currentTimeMillis(); 
    Map<String, String> hashmap = new HashMap<String, String>(); 
    for (int i = 0; i < testnumber; i++) 
    { 
     hashmap.put(Long.toHexString(secureRandom.nextLong()), "true"); 
    } 
    long endtimemap = System.currentTimeMillis(); 
    System.out.println("Time taken map add: " + (endtimemap - starttimemap) + "ms"); 

    // HashSet 
    long starttimeset = System.currentTimeMillis(); 
    Set<String> hashset = new HashSet<String>(); 

    for (int i = 0; i < testnumber; i++) 
    { 
     hashset.add(Long.toHexString(secureRandom.nextLong())); 
    } 

    long endtimeset = System.currentTimeMillis(); 
    System.out.println("Time taken set add: " + (endtimeset - starttimeset) + "ms"); 
} 

回答

2

原因是JVM的工作方式。 JIT编译器需要一些时间,因为它决定根据执行计数编译哪个代码。

因此,第二遍更快是非常自然的,因为JIT已经将很多Java代码编译为本机代码。

如果使用-Xint选项(禁用JIT)启动程序,则两次运行在执行时间内应该大致相等。

2

一个可能的原因是您在执行基准测试之前没有对JIT进行热身。

基本上,Java在一段时间内执行字节码(稍微慢一些),然后才弄清楚经常使用什么来证明JIT将其编译为本地机器代码(这是更快的)。因此,首先发生的事通常会变慢。

在开始真正的基准测试之前,运行这两件事情,让它有机会JIT相关的代码。

0

您没有得到不同的执行时间,您得到相同的执行时间。无论您使用的是HashMap还是HashSet,您都可以在第一次循环中获得相同的时间,而在第二次循环中获得相同的时间。第一个和第二个之间的区别已经被解释了,这是由于JVM的优化。毫无疑问,您是否使用HashMapHashSet作为HashSet在内部使用HashMap并不重要。你一直在执行相同的代码。