Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     

QuestPond: Interview Questions and Answers on learning Design Pattern in .NET

Can you explain 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 initiallyand then on demand basis load the “Order” object.

public class Customer
private List _Orders= null;
public Customer()
            _CustomerName = "Shiv";
            _Orders = LoadOrders(); // Loads the address object even though //not needed

private List LoadOrders()
            List temp = new List();
            Order o = new Order();
            o.OrderNumber = "ord1001";
            o = new Order();
            o.OrderNumber = "ord1002";
            return temp;

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).

Customer o = new Customer(); // Address object not loaded
foreach (Order o1 in o.Orders) // Load address object only at this moment

What are the advantages/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 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.

See following video on Lazy Loading Design Pattern: -

Click and see here stuffs for Senior Developers.

Helpful Website Url
Share this article   |    Print    |    Article read by 4184 times
Shivprasad koirala Koirala
I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. Do visit my site for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers
Related Articles: No related article
Related Interview Questions: No related interview question