Java autoboxing性能比较

Tim*_*çin -1 java performance autoboxing

    // 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");
Run Code Online (Sandbox Code Playgroud)

嗨,我正在阅读有效的Java,并且Item 6:Avoid creating unnecessary objects有一个例子,建议将原语用于盒装基元以避免不必要的对象创建.

作者说,"将总和的声明从长到长改为将我的机器上的运行时间从43秒减少到6.8秒." 并继续说,"教训很明确:更喜欢原始形式的盒装基元,并注意无意识的自动装箱 ".

但是当我在我的机器上运行它时,原始版本比盒装版本慢.

上述程序的输出:

之花:5905毫秒

长期采取:7013毫秒

结果不像作者所说的那样预期,"变量sum被声明为Long而不是long,这意味着程序构造了大约2 ^ 31个不必要的Long实例(每次添加long i时大约一个)长篇)".

为什么使用原始比使用对象慢?

web*_*ter 8

您没有重置第二次测量的起点.原始性能实际上是两个值的时间差(这明显优于包装器).试试这个:

// 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");
Run Code Online (Sandbox Code Playgroud)