I. Introduction
In general, it is better to reuse an object instead of creating a new object with the same function every time you need it, especially when the object is unchangeable, it can always be reused. Reusing objects plays an important role in program performance.
2. Reuse immutable objects
For immutable classes that provide both static factory methods and constructors, you can usually use static factory methods instead of constructors to avoid creating unnecessary objects.
Boolean b1 = Boolean. valueOf ("test"); // use the static factory method (good) Boolean b2 = new Boolean ("test"); // use the constructor (bad)
3. Reuse variable objects that will not be modified
The following example shows whether a person was born on January 1, 1946 ~ From January 1, 1964.
/** Before improvement */public class Person {private Date birthDate = new Date (); public boolean isBabyBoomer () {Calendar calendar = Calendar ar. getInstance (TimeZone. getTimeZone ("GMT"); calendar. set (1946, Calendar. JANUARY, 1, 0, 0, 0); Date boomStart = calendar. getTime (); calendar. set (1965, Calendar. JANUARY, 1, 0, 0, 0); Date boomEnd = calendar. getTime (); return birthDate. compareTo (boomStart)> = 0 & birthDate. compareTo (boomEnd) <0 ;}}
/** Improved */public class Person2 {private Date birthDate = new Date (); private static Date BOOM_START; private static Date BOOM_END; static {Calendar calendar AR = Calendar ar. getInstance (TimeZone. getTimeZone ("GMT"); calendar. set (1946, Calendar. JANUARY, 1, 0, 0, 0); BOOM_START = calendar. getTime (); calendar. set (1965, Calendar. JANUARY, 1, 0, 0, 0); BOOM_END = calendar. getTime ();} public boolean isBabyBoomer () {return birthDate. compareTo (BOOM_START)> = 0 & birthDate. compareTo (BOOM_END) <0 ;}}
Each time isBabyBoomer is called before the improvement, a Calendar, TimeZone, and Date object will be created. The improved program will only create these objects once during initialization. If the isBabyBoomer method is frequently called, the performance will be significantly improved.
Iv. Automatic packing and unpacking
Looking at this small program under the hacker, I wonder if you can find any problems?
public class Client {public static void main(String[] args) {long start = System.currentTimeMillis();Long sum = 0L;for (long i = 0; i < Integer.MAX_VALUE; i++) {sum += i;}long end = System.currentTimeMillis();System.out.println(">>>>>>>>>>Total spent time: " + (end - start) / 1000 + "s");}}
Because sum is defined as the Long type, this program creates many unnecessary objects, and an instance is created every time Long I is added to long sum.
Conclusion: The basic data type rather than the basic packing type should be used first, and the automatic packing should be careful.