New //DON ' T do this!
The improved version is simply the following:
String s = "Stringette";
According to the birthday to determine whether it was born in the baby Boomers, Isbabyboomer () is a bad design, each call to this method will create a Calendar,timezone and 2 Date object instances, when this method is frequently called will greatly affect performance.
Public classPerson {Private FinalDate birthDate; //DON ' T do this! Public BooleanIsbabyboomer () {//unnecessary allocation of expensive object CalendarGmtcal =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); Date boomend=Gmtcal.gettime (); returnBirthdate.compareto (Boomstart) >= 0 &&Birthdate.compareto (boomend)< 0; }}
This is the optimized method, the improved version of the person class creates Calendar, TimeZone, and Date instances only once
These objects are not modified after initialization
classPerson {Private FinalDate birthDate; /*** The starting and ending dates of the baby boom. */ Private Static FinalDate Boom_start; Private Static FinalDate 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 BooleanIsbabyboomer () {returnBirthdate.compareto (Boom_start) >= 0 &&Birthdate.compareto (boom_end)< 0; }}
Autoboxing (Automatic boxing) also has a very large performance impact
// hideously Slow program! Can you spot the object creation? Public Static void Main (string[] args) { = 0L; for (long i = 0; i < Integer.max_value; i++) { + = i ; } SYSTEM.OUT.PRINTLN (sum);}
Java creation object >5.avoid creating unnecessary objects