Creating and destroying objects

Source: Internet
Author: User

1. How to let a class not be instantiated

You should ensure that there are only private constructors in the class.

Because if the class does not contain an explicit constructor, the compiler will automatically provide a public parameterless constructor, so the class must have a constructor.

And these constructors must also be private types, or they will be instantiated or sub-typed.

2. Avoid creating unnecessary objects 2.1 reusing objects

If an object needs to be reused, you can pre-build the instance to avoid creating unnecessary duplicate objects. You can refer to the singleton mode.

Creates a Boolean object based on a Boolean value, each time a call is created with a new object.

New Boolean (true);

Take a look at some of the code for the Boolean class: The ValueOf () method reuses pre-built instances, and these instances do not change, so it is not always a good practice to create new objects.

 Public Final classBooleanImplementsJava.io.serializable,comparable<boolean>{     Public Static FinalBoolean TRUE =NewBoolean (true);  Public Static FinalBoolean FALSE =NewBoolean (false);  Public StaticBoolean ValueOf (Booleanb) {return(b?true:false); }}

Here is another example:

 Public class   dateutil{    publicstatic  String getDate () {        new SimpleDateFormat ("Yyyy-mm-dd");         return Df.format (new  Date ());}    }

In the above code, each call to the GetDate () method creates a SimpleDateFormat object, and we can extract the code to get the following:

 Public class   dateutil{    privatestaticnew SimpleDateFormat ("Yyyy-mm-dd");          Public Static String getDate () {        return df.format (new  Date ());}    }

But is this code really good? If I don't call the GetDate () method, what's the use of my pre-built instance, not wasting storage space and time?

Workaround: You can defer initialization of it, as follows:

 Public class   dateutil{    privatestaticnull;          Public Static String getDate () {        if(null= =df)            {new SimpleDateFormat ("Yyyy-mm-dd");        }         return Df.format (new  Date ());}    }

Of course, the code becomes a little more complicated.

So, in terms of the complexity and performance of the code, we have to make a trade-off, such as the above-mentioned code is no effect on performance, so there is no need to make the code so complicated. In short, it depends on the situation.

2.2 Using String correctly

Try not to create a String object as follows, creating a new instance each time and then returning a reference to the instance.

New String ("abc");

A better way to do this is if the JVM's constant pool has exactly the string object "ABC", it will not create any objects and then return a reference to the "ABC" string object.

String str = "ABC";

2.3 Priority use of basic types

You prefer to use the base type instead of the boxed base type.

 Public Static voidMain (string[] args) {Long L1= 10L; LongL2 = 10L; Integer I1= 1; intI2 = 1; Calendar C1=calendar.getinstance ();  for(inti=0;i<1000000000;i++) {L1+=I1; } Calendar C2=calendar.getinstance ();  for(inti=0;i<1000000000;i++) {L1+=I2; } Calendar C3=calendar.getinstance ();  for(inti=0;i<1000000000;i++) {L2+=I1; } Calendar c4=calendar.getinstance ();  for(inti=0;i<1000000000;i++) {L2+=I2; } Calendar c5=calendar.getinstance (); System.out.println (C2.gettimeinmillis ()-C1.gettimeinmillis ()); System.out.println (C3.gettimeinmillis ()-C2.gettimeinmillis ()); System.out.println (C4.gettimeinmillis ()-C3.gettimeinmillis ()); System.out.println (C5.gettimeinmillis ()-C4.gettimeinmillis ());}

The above code is finally output as follows:

45564305343328

The calculation process for the first loop:

    • L1-type long, i1-type int;
    • I1-long type, added with L1 to get a long type;
    • Will get the long and long after the continuation of the loop;

The calculation process for the second loop:

    • L1-long type;
    • I2-long type, added with L1 to get a long type;
    • Will get the long and long after the continuation of the loop;

The third cycle of the calculation process:

    • i1 type int;
    • I1-long type, with L2 added to get a long type after the continuation of the loop;

The calculation process for the fourth cycle:

    • I2-long type, with L2 added to get a long type after the continuation of the loop;

Conclusion: The basic type is preferred when the boxed base type is converted to the basic type before the operation is done.

3. Elimination of expired object references

Remember to recycle when you're done with the object.

Here is a piece of code for the Stack in an older version of the JDK:

 Public classStack {Privateobject[] elements; Private intSize = 0; Private Static Final intDefault_initial_capacity = 16;  PublicStack () {Elements=NewObject[default_initial_capacity]; }     Public voidpush (Object e) {ensurecapacity (); Elements[size++] =e; }     PublicObject Pop () {if(Size = = 0)            Throw Newemptystackexception (); returnelements[--size]; }    /*** Ensure space for at least one more element, roughly doubling the capacity * each time the array needs to GR     ow. */    Private voidensurecapacity () {if(Elements.length = =size) Elements= arrays.copyof (Elements, 2 * size + 1); }}

It is not difficult to find that if a stack is first grown and then contracted, then the object ejected from the stack will not be garbage collected.

You can solve this problem by modifying the Pop () method. This problem has been solved in the current JDK version.

 Public Object Pop () {    if (size = =0        )thrownew  emptystackexception ( );     = elements[--size];     NULL ;     return elements[--size];}

In general, you should be aware of memory leaks when managing memory like a Stack.

Creating and destroying objects

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.