Sunday, November 11, 2012

Lazy Loading or Lazy Initialization




It is the strategy of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
This can be done by maintaining a flag indicating whether the process has taken place or not. Each time the desired object is accessed, the flag is tested. If it is ready, it is returned. If not, it is initialized on the spot.
Object creation  and keeping them is one of the most expensive operation in terms of memory utilization and performance impact. It is thus advisable to create or initialize an object only when it is required in the code.
Example:


public class Employee {

    private List employeeList;
     
    public List getEmployees() {
         
        //initialize only when required
        if(null == employeeList) {
            employeeList = new ArrayList();
        }
        return employeeList;
    }
}

No comments:

Post a Comment