Java之建立物件>5.Avoid creating unnecessary objects

FrankYou發表於2017-05-27
String s = new String("stringette"); // DON'T DO THIS!

The improved version is simply the following:

String s = "stringette";

根據生日來判斷是否是嬰兒潮時期出生的,isBabyBoomer()是一個糟糕的設計,每次呼叫這個方法都會建立Calendar,TimeZone以及2個Date物件例項,當此方法被頻繁呼叫時將會非常地影響效能。

public class Person {
    private final Date birthDate;
  
    // DON'T DO THIS!
    public boolean isBabyBoomer() {
        // Unnecessary allocation of expensive object
        Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
        Date boomStart = gmtCal.getTime();
        gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
        Date boomEnd = gmtCal.getTime();
        return birthDate.compareTo(boomStart) >= 0 &&
        birthDate.compareTo(boomEnd) < 0;
    }
}

這個是優化後的方法,The improved version of the Person class creates Calendar, TimeZone, and Date instances only once

這些物件都是初始化後不會再被修改

class Person {
    private final Date birthDate;
    /**
    * 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;
    }
}

autoboxing(自動裝箱)也會帶來非常大的效能影響

 // Hideously slow program! Can you spot the object creation?
public static void main(String[] args) {
    Long sum = 0L;
    for (long i = 0; i < Integer.MAX_VALUE; i++) {
        sum += i;
    }
    System.out.println(sum);
}

 

相關文章