Valid Item 3-avoid unnecessary objects

Source: Internet
Author: User

Generally, we prefer to reuse an object rather than recreate it.

If the object is unchangeable, it can always be reused.


The following is a negative example. Joshua Bloch explicitly states [don't to this]:

String s = new String("stringette");

This statement creates a new instance each time it is executed.

The parameter "stringette" in the string constructor is an instance,FunctionsIt is equivalent to the objects created by the constructor.

If such a statement is placed in a loop, the effect will become worse.


So we only need:

String s = "stringette";

In this way, it will always be the same string instance, and it can ensure that the same VM will reuse the same string literal object.

(The object will be reused by any other code running in the same vitual machine that happens to contain the same string literal .)


If both the static factory method and constructor are provided in the class, the client can usually use the static factory method to prevent unnecessary objects from being created.

For example, java. Lang. boolean:

public static final Boolean TRUE = new Boolean(true);  public static final Boolean FALSE = new Boolean(false);   public static Boolean valueOf(boolean b) {    return (b ? TRUE : FALSE);}


The corresponding descriptions are also made in the javadoc of the constructor:

    /**     * Allocates a {@code Boolean} object representing the     * {@code value} argument.     *     * <p><b>Note: It is rarely appropriate to use this constructor.     * Unless a <i>new</i> instance is required, the static factory     * {@link #valueOf(boolean)} is generally a better choice. It is     * likely to yield significantly better space and time performance.</b>     *     * @param   value   the value of the {@code Boolean}.     */    public Boolean(boolean value) {        this.value = value;    }


In addition to reusing immutable objects, we can also reuse variable objects that will not change.

(Also use mutable object if you know they won't be modified .)


The following is a negative example to check whether a person is born at the birth peak (1946 ~ 1964 ):

import java.util.Calendar;import java.util.Date;import java.util.TimeZone;public class Person {private final Date birthDate;public Person(Date birthDate) {// Defensive copy - see Item 39this.birthDate = new Date(birthDate.getTime());}// Other fields, methods omitted// DON‘T DO THIS!public boolean isBabyBoomer() {// Unnecessary allocation of expensive objectCalendar 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();return birthDate.compareTo(boomStart) >= 0&& birthDate.compareTo(boomEnd) < 0;}}


One calendar ar. getinstance and two gettime will create a new instance:

    public static Calendar getInstance(TimeZone zone,Locale aLocale){        return createCalendar(zone, aLocale);    }     private static Calendar createCalendar(TimeZone zone,Locale aLocale){        Calendar cal = null;        String caltype = aLocale.getUnicodeLocaleType("ca");        if (caltype == null) {            // Calendar type is not specified.            // If the specified locale is a Thai locale,            // returns a BuddhistCalendar instance.            if ("th".equals(aLocale.getLanguage())                    && ("TH".equals(aLocale.getCountry()))) {                cal = new BuddhistCalendar(zone, aLocale);            } else {                cal = new GregorianCalendar(zone, aLocale);            }        } else if (caltype.equals("japanese")) {            cal = new JapaneseImperialCalendar(zone, aLocale);        } else if (caltype.equals("buddhist")) {            cal = new BuddhistCalendar(zone, aLocale);        } else {            // Unsupported calendar type.            // Use Gregorian calendar as a fallback.            cal = new GregorianCalendar(zone, aLocale);        }        return cal;    }         public final Date getTime() {        return new Date(getTimeInMillis());    }


So let's make some improvements, declare the object as Private Static final, and prepare all the instances in the static initialization block:

import java.util.Calendar;import java.util.Date;import java.util.TimeZone;class Person {private final Date birthDate;public Person(Date birthDate) {// Defensive copy - see Item 39this.birthDate = new Date(birthDate.getTime());}// Other fields, methods/** * The starting and ending dates of the baby boom. */private static final Date BOOM_START;private static final Date 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 boolean isBabyBoomer() {return birthDate.compareTo(BOOM_START) >= 0&& birthDate.compareTo(BOOM_END) < 0;}}

This not only improves efficiency, but also makes it clearer.


However, we can make some improvements.

If isbabyboomer in the above example has not been called, The instance we created in the static initialization block will be wasted (maybe there are too few objects in the example, ).

To solve this problem, we can use lazily initializing to initialize isbabyboomer when it is called for the first time.

However, the author does not recommend this because it may only make the method implementation more complex without significantly improving the efficiency.


In the above example, we will not change the reusable object after instantiation. Can we reuse the variable object?

For example, the map. keyset method returns the same set instance. The status of this set instance depends on its backing object, that is, the map instance.

Set also changes when map changes.

Although it is feasible to re-create a set instance for each call, it is not necessary.


In addition, the autoboxing feature also provides users with new methods to create unnecessary objects.

Try mixing the basic and encapsulation types and make them out of the cache range of the encapsulation type.

For example:

public class Sum {// Hideously slow program! Can you spot the object creation?public static void main(String[] args) {Long sum = 0L;for (long i = 0; i < Integer.MAX_VALUE; i++) {sum += i;}System.out.println(sum);}}

It only declares the sum type as long, causing a huge waste.

(Prefer primitives to boxed primitives, and watch out for unintentional autoboxing .)




This article is from the "map. Get (x) = new object ()" blog, be sure to keep this source http://runtime.blog.51cto.com/7711135/1433419

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.