Java autoboxing性能比较

时间:2014-08-11 07:16:38

标签: 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");

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

作者说,“将总和的声明从长到长更改会将运行时从43秒减少到6.8 秒。”并继续,“教训很清楚:更喜欢基元到盒装基元,并注意无意识的自动装箱

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

上述程序的输出:

  

总和: 5905 毫秒

     

总和: 7013 毫秒

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

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

1 个答案:

答案 0 :(得分: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");