Effective Java to avoid creating unnecessary objects and eliminating outdated references

Source: Internet
Author: User

Why avoid creating unnecessary objects? The process of creating objects is still more cost-intensive, according to the performance tests given in the book, the time consuming to recreate objects is 250 times times the time consumed by reusing objects. The following is a list of scenarios where objects can be reused.

1, String type Note that there is a big difference between string s = "as" and string s = new String ("as"), and the second method of creating a string instance will actually produce two "as" objects.

2. For mutable objects that are known not to be modified, they can be initialized only on first use, not each time they are used.

3, priority to use basic types, such as Int,long, rather than boxing basic type Integer,long, etc., because each use of boxing basic type, it takes a certain amount of time and memory to create its object.

The JVM will automatically help us clean up inaccessible objects, but if an object in an array we will never use, and if we do not control him, then that object will always reside in memory, should be stored in the array object is still there, in this case, in order to use the object is not used in a timely manner to null.

Note: Know there is a gap, did not expect the gap so big.

  

Effective Java to avoid creating unnecessary objects and eliminating outdated references

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.