(第五条)避免创建不必要的对象

对比创建没必要的对象:

public class Person {

    private Date birthDate = new Date();

    public boolean isBabyBoomer(){
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        cal.set(1946,Calendar.JANUARY,1,0,0,0);
        Date boomStart =cal.getTime();
        cal.set(1965,Calendar.JANUARY,1,0,0,0);
        Date boomEnd =cal.getTime();
        return birthDate.compareTo(boomStart) >=0 && birthDate.compareTo(boomEnd) < 0;
    }
}

上述方法循环执行1000W次消耗3.8秒左右,上述方法我们每次都需要新建一个Calendar、一个TimeZone、2个Date。下边我们使用static初始化尝试一下:

public class Person {

    private Date birthDate = new Date();
    private static final Date BOOM_START;
    private static final Date BOOM_END;
    static {
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        cal.set(1946,Calendar.JANUARY,1,0,0,0);
        BOOM_START =cal.getTime();
        cal.set(1965,Calendar.JANUARY,1,0,0,0);
        BOOM_END =cal.getTime();
    }

    public boolean isBabyBoomer(){
        return birthDate.compareTo(BOOM_START) >=0 && birthDate.compareTo(BOOM_END) < 0;
    }
}

使用static代码块之后循环1000W次只需要0.018秒左右

  总结如下:

      1.对于多次重用的对象并且初始化之后不会再改变可以考虑在静态区域生成。

      2.当你应该重用现有对象的时候,请不要创建新的对象。

posted @ 2017-08-11 16:42  lkf00889  阅读(103)  评论(0编辑  收藏  举报