What is Lazy loading ?
Lazy loading is a concept where we delay the loading of the object unit the point where we need it. Putting in simple words on demand object loading rather than loading the objects unnecessarily.
For example consider the below example where we have a simple “Customer” class and this “Customer” class has many “Order” objects inside it. Have a close look at the constructor of the “Customer” class. When the “Customer” object is created it also loads the “Order” object at that moment. So even if we need or do not need the address object, it’s still loaded.
But how about just loading the “Customer” object initially and then on demand basis load the “Order” object.
So let’s consider you have client code which consumes the “Customer” class as shown below. So when the “Customer” object is created no “Order” objects should be loaded at that moment. But as soon as the “foreach” loop runs you would like to load the “Order” object at that point ( on demand object loading).
So how do we implement “LazyLoading” ?
So for the above example if we want to implement Lazy loading we will need to make the following changes:-
- Remove the “Order” object loading from the constructor.
- In the “Order” get property, load the “Order” object only if it’s not loaded.
Now if you run the client code and halt your debugger just before the “ForEach” loop runs over the “Orders” object, you can see the “Orders” object is null ( i.e. not loaded). But as soon as the “ForEach” loop runs over the “Order” object it creates the “Order” object collection.
Are there any readymade objects in .NET by which we can implement Lazy loading?
In .NET we have “Lazy
Create the object of orders using the “Lazy” generic class.
Attach this Lazy<> object with the method which will help us load the order’s data.
Now as soon as any client makes a call to the “_Orders” object ,it will call the “LoadOrders” function to load the data.
You will get the “List
” data in the “Value”
Below goes the full code for the same.
What are the advantages and disadvantages of lazy loading?
Below are the advantages of lazy loading:-
- Minimizes start up time of the application.
- Application consumes less memory because of on-demand loading.
- Unnecessary database SQL execution is avoided.
The only one disadvantage is that the code becomes complicated. As we need to do checks if the loading is needed or not. So must be there is a slight decrease in performance.
But the advantages of are far more than the disadvantages.