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