Reuse Objects instead of creating new ones if possible
Object creation is an expensive operation in Java, with impact on both performance and memory utilization.The cost varies depending on the amount of initialization that needs to be performed when the object is created.Way to minimize excess object creation are
- Use a pool to share resource objects
- Recycle Objects
- Use Lazy initialization of object
The resource objects are Threads, JDBC connections, sockets and complex user defined objects. They are expensive to create, and pooling them reduce the overhead of repetitively creating and destroying.On the down side, using a pool means you must implement the code to manage it and pay overhead of synchronization when you get or remove objects from the pool, but the overall performance gains if you get from using pool to manage expensive resource object outweighs that overhead.
However, be cautious on implementing a resource pool.The following mistakes in pool management are often observed:
- a resource object which should be used only serially is given to more than one user at the same time
- objects that are returned to the pool are not properly accounted for and are therefore not reused, wasting resources and causing a memory leak
- element or objects references kept in the pool are not reset or cleaned up properly being given to next user.
Recycle Objects
Recycle object is similar to creating an object pool, but there is no need to manage it because the pool only has one object. This approach is most useful for relatively large container objects (such as Vectors or Hashtable ) that you want to use for holding some temporary data.Reusing of objects instead of creating new ones each time avoid memory allocation and reduce garbage collection.
Similar to using a pool, you must take precautions to clear all the element in any recycled object before you reuse it to avoid memory leak.The collection interface have built-in clear() method that you can use.If you are building your objects, you should remember to include a reset() or clear() method if necessary.
Use lazy initialization to defer creating the object until you need it
Defer creating an object until its is needed if the initialization of the object is expensive or if the objects is needed only some specific condition.
Example
import java.util.ArrayList;
import java.util.List;
public class JavaTutorialsCorner {
private List tutorials= null;
public List getTutorials(){
if(tutorials == null){
tutorials = new ArrayList<>();
}
return tutorials;
}
}
0 comments:
Post a Comment