2013-11-22 49 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並不重要。你一直在執行相同的代碼。