Item 5: Avoid creating unnecessary objects

1.    An object can always be reused if it is immutable

 

2.    The statement: 

String s = new String("stringette");

 creates a new String instance each time it is executed, and none of those object creations is necessary.

 

3.    You can often avoid creating unnecessary objects by using static factory methods in preference to constructors on immutable classes. (Boolean.valueOf() over Boolean(boolean) )

 

4.    You can also reuse mutable objects if you know they won’t be modified.

 

5.    If you don’t change local objects after initialization in the method, you can declare them as final static instead of local variables and initialize them in the static initializer so that you can reuse them instead of create new instances of them in the method.


6.    An adapter is an object that delegates to a backing object, providing an alternative interface to the backing object. Because an adapter has no state beyond that of its backing object, there’s no need to create more than one instance of a given adapter to a given object. i.e. The keySet method of the Map interface returns a Set view of the Map object, consisting of all the keys in the map. Naively, it would seem that every call to keySet would have to create a new Set instance, but every call to keySet on a given Map object may return the same Set instance. Although the returned Set instance is typically mutable, all of the returned objects are functionally identical: when one of the returned objects changes, so do all the others because they’re all backed by the same Map instance. While it is harmless to create multiple instances of the keySet view object, it is also unnecessary.

 

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

 

8.    The creation and reclamation of small objects whose constructors do little explicit work is cheap, especially on modern JVM implementations. (Small and short lived objects are easy to collect in young generation.)

 

9.    Avoiding object creation by maintaining your own object pool is a bad idea unless the objects in the pool are extremely heavyweight (i.e. database connections).

你可能感兴趣的:(Effective Java)