代码之家  ›  专栏  ›  技术社区  ›  Timuçin

Java自动装箱性能比较

  •  0
  • Timuçin  · 技术社区  · 10 年前
        // 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");
    

    嗨,我正在阅读有效的Java和 Item 6:Avoid creating unnecessary objects ,有一个示例建议将原语转换为盒装原语,以避免不必要的对象创建。

    作者说, “将sum的声明从Long更改为Long会减少运行时间 从43秒到6.8秒 在我的机器上几秒钟。" 并且继续, “教训很清楚: 与装箱基元相比,更喜欢基元,并注意无意中的自动装箱 " .

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

    上述程序的输出:

    长的 所取金额: 5905 毫秒

    长的 所取金额: 7013 毫秒

    结果并不像作者所说的那样令人期待, 变量和被声明为Long而不是Long,这意味着程序构造了大约2^31个不必要的Long实例(大约每次将Long i添加到Long和中时一个) .

    为什么使用基本体比使用对象慢?

    1 回复  |  直到 4 年前
        1
  •  9
  •   webuster    10 年前

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

    // 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");