簡體   English   中英

根據執行順序,HashMap和HashSet的執行時間不同嗎?

[英]Different execution time for HashMap and HashSet based on the order of execution?

如果我將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");
}

原因是JVM的工作方式。 JIT編譯器需要一些時間才能啟動,因為它會根據執行次數來決定要編譯的代碼。

因此,第二遍更快是很自然的,因為JIT已經將很多Java代碼編譯為本地代碼。

如果使用-Xint選項(禁用JIT)啟動程序,則兩次運行的執行時間應大致相等。

一個可能的原因是您沒有在執行基准測試之前對JIT進行預熱。

基本上,Java將執行字節碼(稍慢一些),然后找出足夠經常使用的東西以證明JIT將其編譯為本地機器代碼(更快)是合理的。 因此,首先發生的事情通常會變慢。

在啟動真正的基准測試之前,請多次運行這兩種方法,以便有機會JIT相關代碼。

您沒有得到不同的執行時間,卻得到了相同的執行時間。 無論使用HashMap還是HashSet您都將在第一個循環中獲得相同的時間,而在第二個循環中獲得相同的時間。 第一個和第二個之間的差異已經解釋過了,這是由於JVM的優化所致。 毫不奇怪,使用HashMap還是HashSet都沒有關系,因為HashSet在內部使用HashMap 您一直在執行相同的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM