条目5:避免创建不必要的对象

避免创建不必要的对象


1.自动装箱和拆箱。要优先使用简单数据类型,而不是装箱的简单类型。避免无意识的装箱。

public class Sum {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Long sum = 0L;
        for(int i=0;i<Integer.MAX_VALUE;i++){
            sum+=i;
        }
        long end = System.currentTimeMillis();
        System.out.println("使用Long耗时:="+(end-start));


        long start1 = System.currentTimeMillis();
        long sum1 = 0L;
        for(int i=0;i<Integer.MAX_VALUE;i++){
            sum1+=i;
        }
        long end1 = System.currentTimeMillis();
        System.out.println("使用long耗时:="+(end1-start1));

    }
}

2.重用那些已知的不会修改的可变对象

class Person {
    private final Date birthDate;

    public Person(Date birthDate) {
        // Defensive copy - see Item 39
        this.birthDate = new Date(birthDate.getTime());
    }

    // Other fields, methods

    /**
     * The starting and ending dates of the baby boom.
     */
    private static final Date BOOM_START;
    private static final Date BOOM_END;

    static {
        Calendar gmtCal =
            Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
        BOOM_START = gmtCal.getTime();
        gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
        BOOM_END = gmtCal.getTime();
    }

    public boolean isBabyBoomer() {
        return birthDate.compareTo(BOOM_START) >= 0 &&
               birthDate.compareTo(BOOM_END)   <  0;
    }
}
原文地址:https://www.cnblogs.com/tisakong/p/4476661.html