Friday, July 19

Item 71: Use lazy initialization judiciously



What is lazy initialization ?


 How is it different from normal initialization?

Lazy initialization adds delay to the time an instance or static variable gets initialized.


 How much delay?

Initialization can be delayed as long as it is not required in our execution.

Why would you delay that ?

There might be a possibility that instance might not be required at all. In that case there is not only a performance gain but also you are avoiding allocating memory unnecessarily.

Then Why do you need to be Judicious? Why can't we consider it as a default principal to use lazy initialization in every case.

Lets understand that with a code snippet

Public class Car {

        private Tyre tyre ;

     public Tyre getTyreInstance(){

              if(tyre==null){

                 tyre=new Tyre()
              }

              return tyre;

           }
}

What is happening here. First we are checking If instance is null or not . So this execution of If statement is happening in every case . If there are too many instances required tyre are required multiple execution of this if check may deteriorates the overall performance instead of increasing depending upon how much complexity is involved in instance initialization. On the other hand if there are only a few instances of tyre are required , performance save on part of lazy initialization may be much more than that of performance loss in if statement execution.

So we need to be highly judicious while using lazy initialization.

Now how will we decide practically whether to use it or not in a given scenario. Simple answer is measure the performance with and without lazy initialization ,compare and use the option resulting in overall better performance.

Effective java Simplified

No comments:

Post a Comment