1. 程式人生 > >避免自動裝箱

避免自動裝箱

class sta 基本類型 nbsp void stat art get pub

public class Person {

  public static void main(String[] args) {
    // TODO Auto-generated method stub

    //較差
    Date start = new Date();
    Long sum = 0L;
    for(int i = 0,max = 1000000; i < max; i++) {
      sum += 5;
    }
    Date end = new Date();
    
    System.out.println("用時: " + (end.getTime() - start.getTime()));
    
    //較好
    start = new

Date();
    long sum1 = 0L;
    for(int i = 0,max = 1000000; i < max; i++) {
      sum1 += 5;
    }
    end = new Date();

    System.out.println("用時: " + (end.getTime() - start.getTime()));
    
  }

}

輸出結果:

用時: 18
用時: 2

要優先使用基本類型而不是裝箱基本類型,要當心無意識的自動裝箱

避免自動裝箱