It is often appropriate to reuse a single object instead of creating a new functionally equivalent object each time it is needed. Reuse can be both fast and more stylish. An object can always be reused if it is immutable.
String s = new String(“string”); // DON’T DO THISThe statement create a new String instance each time it is executed, and none of those object creation is necessary. The argument to the String constructor (“string”) is itself a String instance.
class Person { private final Date birthDate; ... //DON'T DO THIS public boolean isBabyBoomer() { // Unnecessary allocation of expensive object Calendar gmtCalendar = Clanedar.getInstance(TimeZone.getTimeZone("GMT")); gmtCalendar.set(1946, Calendar.JANUARY, 1, 0, 0, 0); Date boomStart = gmtCalendar.getTime(); gmtCalendar.set(1965, Calendar.JANUARY, 1, 0, 0, 0); Date boomEnd = gmtCalendar.getTime(); return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0; }
The isBabyBoomer method unnecessarily create a new Calendar, TimeZone and two Date instances each time is is invoked. The version that follows avoids this inefficiency:
class Person { private static final Date BOOM_START; private static final Date BOOM_END; private final Date birthDate; static { Calendar gmtCalendar = Clanedar.getInstance(TimeZone.getTimeZone("GMT")); gmtCalendar.set(1946, Calendar.JANUARY, 1, 0, 0, 0); BOOM_START = gmtCalendar.getTime(); gmtCalendar.set(1965, Calendar.JANUARY, 1, 0, 0, 0); BOOM_END = gmtCalendar.getTime(); } public boolean isBabyBoomer() { return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0; } }
The improved version of the Person class creates Calendar, TimeZone and Date instance only once, when it is initialized, instead of creating them every time isBabyBoomer is invoked.