1. If the object is immutable (immutable), it can always be reused.
(1) In particular, objects of type string.
New // create a number of unnecessary instances // "STR" is itself a string instance, and the object is reused for all code running in the same virtual machine as long as they contain the same string literal constant .
(2) An immutable class of static factory methods and constructors is provided, often using static factory methods rather than constructors.
2. If a mutable object is known not to be modified, it can also be reused.
ImportJava.util.Calendar;Importjava.util.Date;ImportJava.util.TimeZone; Public classPerson {Private FinalDate birthday; // ... Public BooleanIsbabyboomer () {Calendar gmtcal = 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 (); returnBirthday.compareto (Boomstart) >= 0 &&Birthday.compareto (boomend)< 0; }}
If Isbabyboomer () is often called, it is inefficient to create an instance of Calendar,date every time. Performance is improved in the following ways, and the meaning of the code is more clear.
ImportJava.util.Calendar;Importjava.util.Date;ImportJava.util.TimeZone; Public classPerson {Private FinalDate birthday; 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 () {returnBirthday.compareto (Boom_start) >= 0 &&Birthday.compareto (boom_end)< 0; }}
New method for creating extra objects: Auto-boxing (autoboxing). However, to take precedence over the basic type rather than the boxed base type, beware of involuntary automatic boxing, or create multiple redundant instances.
(in response to 39th) the cost of reusing objects is far greater than the cost of creating duplicate objects, advocating the use of protective copies .
For example, do not maintain your own object pool unless the objects in the pool are very heavyweight (database connection pooling). Generally maintaining your own pool of objects is bound to confuse the code, increasing memory consumption, and compromising performance.
Failure to implement a protective copy when necessary can lead to potential errors and security breaches .
Unnecessary creation of objects can affect the style and performance of the program .
"Reading notes-effective Java" 05. Avoid creating unnecessary objects