First, a primer
In general, it is better to reuse an object than to create a new object of the same functionality every time you need it, especially if the object is immutable and can always be reused. Reusing objects plays an important role in program performance.
Second, reuse immutable objects
For immutable classes that provide both static factory methods and constructors, you can often 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 Constructor (bad)
Iii. reusing mutable objects that will not be modified
The following example business is: testing whether someone was born in 1946 ~ 1964.
/* * before the improvement */public class Person {private Date birthdate = new Date ();
public Boolean Isbabyboomer () {Calendar calendar = calendar.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; }
}
* * * after the improvement *
/public class Person2 {
private date birthdate = new Date ();
private static Date Boom_start;
private static Date boom_end;
static {
Calendar calendar = calendar.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;
}
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/Java/
Each call to Isbabyboomer creates a Calendar,timezone,date object before it is improved, and the improved program creates the objects only once at initialization time. If the Isbabyboomer method is invoked frequently, performance will be significantly improved.
Four, automatic boxing and unpacking
Look at the following small program, I do not know 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 a long, this program creates a lot of unnecessary objects, and an instance is built each time a long I is added to long sum.
Conclusion: In order to prioritize the use of basic data types rather than boxing basic types, beware of automatic boxing of the unconscious.
Author: csdn Blog zdp072