JAVA: avoid repeated object creation.
In actual development, it is much better to use the same object repeatedly than to create an object each time;
As an extreme negative example, let's look at the following statement:
String s = new String ("haha ");
A new String instance will be created each time the statement is executed. If this is used in a loop or in a frequently called method, tens of thousands of String instances will be created. This method is unnecessary and can be changed to the following:
String s = "haha ";
This version only uses one String instance, instead of creating one instance each time it is executed. For code running in the same virtual environment, the modified object will be reused as long as it contains the same string literal constant.
In addition to reusing mutable objects, you can also reuse variable objects that are not known to be modified. See a common example:
1 public class Person{ 2 private final Date birthDate; 3 4 public Person(Date birthDate){ 5 this.birthDate = birthDate; 6 } 7 8 public boolean isBabyBoomer(){ 9 Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));10 11 gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);12 Date boomStart = gmtCal.getTime();13 14 gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);15 Date boomEnd = gmtCal.getTime();16 17 return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0;18 }19 20 }
Every time isBabyBoomer is called, a new Calendar, a new TimeZone, and two new Date objects are created. This is not necessary. The following version uses a static initiator, this avoids the inefficiency in the above example:
1 public class Person{ 2 private final Date birthDate; 3 4 public Person(Date birthDate){ 5 this.birthDate = birthDate; 6 } 7 8 private static final Date BOOM_START; 9 private static final Date BOOM_END; 10 11 static{12 Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));13 14 gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);15 BOOM_START = gmtCal.getTime();16 17 gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);18 BOOM_END = gmtCal.getTime();19 } 20 21 public boolean isBabyBoomer(){22 return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0;23 }24 25 }
The Person class of the improved version only creates Calendar, TimeZone, and Date instances at the time of initialization, instead of creating them each time isBadyBoomer is called.
From objective java