Java之創建對象>5.Avoid creating unnecessary objects
阿新 • • 發佈:2017-05-27
alloc spa color win set 根據 優化 ava 生日
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); DateboomEnd = 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 finalDate 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); }
Java之創建對象>5.Avoid creating unnecessary objects