簡體   English   中英

Java自動裝箱性能比較

[英]Java autoboxing performance comparison

    // Hideously slow program! Can you spot the object creation?
    Long sum = 0L;
    for (long i = 0; i < Integer.MAX_VALUE; i++) {
        sum += i;
    }
    end = System.currentTimeMillis();
    System.out.println("Long sum took: " + (end - start) + " milliseconds");

    long sum2 = 0L;
    for (long i = 0; i < Integer.MAX_VALUE; i++) {
        sum2 += i;
    }
    end = System.currentTimeMillis();
    System.out.println("long sum took: " + (end - start) + " milliseconds");

嗨,我正在閱讀Effective Java,在Item 6:Avoid creating unnecessary objects ,有一個示例建議將原語添加到裝箱的原語中,以避免不必要的對象創建。

作者說: “將和的聲明從Long更改為long可以將我的機器上的運行時間從43秒減少到6.8秒。” 並繼續, “課程很明確:相對於裝箱的原語,更喜歡原語,並提防意外的自動裝箱

但是,當我在計算機上運行它時, 原始版本比裝箱的版本要慢

上面程序的輸出:

之花:5905毫秒

總和了:7013毫秒

結果並不像作者所說的那樣預期, “變量sum被聲明為Long而不是long,這意味着程序構造了大約2 ^ 31個不必要的Long實例(每次將long添加到i時大約一個實例)長整數)”

為什么使用原始速度比使用對象慢?

您沒有重置第二次測量的起點。 原始性能實際上是兩個值的時間差(顯然比包裝器的時間差更好)。 嘗試這個:

// Hideously slow program! Can you spot the object creation?
Long sum = 0L;
start = System.currentTimeMillis();
for (long i = 0; i < Integer.MAX_VALUE; i++) {
    sum += i;
}
end = System.currentTimeMillis();
System.out.println("Long sum took: " + (end - start) + " milliseconds");

long sum2 = 0L;

// reset start!!
start = System.currentTimeMillis();

for (long i = 0; i < Integer.MAX_VALUE; i++) {
    sum2 += i;
}
end = System.currentTimeMillis();
System.out.println("long sum took: " + (end - start) + " milliseconds");

暫無
暫無

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

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