Click here to Skip to main content
12,507,845 members (56,015 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

147.2K views
92 bookmarked
Posted

Can you explain Lazy Loading?

, 16 Sep 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Lazy loading is a concept where we delay the loading of the object until the point where we need it.

Introduction

Lazy loading is a concept where we delay the loading of the object until the point where we need it. Putting in simple words, on demand object loading rather than loading 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 Order object, it’s still loaded.

But how about just loading the Customer object initially and then on demand basis load the Order object?

public class Customer
{
	private List<Order> _Orders= null;
	…
	…
	public Customer()
	{
        _CustomerName = "Shiv";
        _Orders = LoadOrders(); // Loads the order object even though //not needed
	}
     
	private List<Order> LoadOrders()
	{
        List<Order> temp = new List<Order>();
        Order o = new Order();
        o.OrderNumber = "ord1001";
        temp.Add(o);
        o = new Order();
        o.OrderNumber = "ord1002";
        temp.Add(o);
        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(); // order object not loaded
Console.WriteLine(o.CustomerName);
foreach (Order o1 in o.Orders) // Load order object only at this moment
{
    Console.WriteLine(o1.OrderNumber);
}

So how do we implement lazy loading?

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.
public class Customer
{
    private List<Order> _Orders= null;
    …
    …
    public Customer()
    {
        _CustomerName = "Shiv";
    }
    public List<Order> Orders
    {
	    get 
        {
            if (_Orders == null)
            {
                _Orders = LoadOrders();
            }
            return _Orders; 
        }
    }

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 the Lazy<T> class which provides automatic support for lazy loading. So let’s say if you want to implement Lazy<> in the above code, we need to implement two steps:

Create the object of orders using the Lazy generic class.

private Lazy<List<Order>> _Orders= null; 

Attach this Lazy<> object with the method which will help us load the order’s data.

_Orders = new Lazy<List<Order>>(() => LoadOrders());  

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<orders> data in the Value property.

public List<Order> Orders
{
    get 
    {
        return _Orders.Value; 
    }
   
} 

Below goes the full code for this:

public class Customer
{
    private Lazy<List<Order>> _Orders= null;
    public List<Order> Orders
    {
        get 
        {
            return _Orders.Value; 
        }
    }
    public Customer()
    {
        // Makes a database trip
        _CustomerName = "Shiv";
        _Orders = new Lazy<List<Order>>(() => LoadOrders());
    }
} 

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, there is a slight decrease in performance.

But the advantages are far more than the disadvantages.

FYI: The opposite of Lazy Loading is eager loading. So in eager loading we load all the objects in memory as soon as the object is created.  

Also have a look at below posted video on Lazy Loading: - 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1072207719-Nov-15 22:33
memberMember 1072207719-Nov-15 22:33 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun27-Aug-15 1:00
memberHumayun Kabir Mamun27-Aug-15 1:00 
GeneralGood article Pin
Thinira21-Apr-15 21:26
memberThinira21-Apr-15 21:26 
Generalgood article Pin
upendra shahi21-Apr-15 20:32
memberupendra shahi21-Apr-15 20:32 
QuestionThree layer architecture Pin
fabio.visin23-Mar-15 6:45
memberfabio.visin23-Mar-15 6:45 
GeneralMy vote of 3 Pin
saumendra111124-Sep-14 2:19
membersaumendra111124-Sep-14 2:19 
QuestionHow garbage collector process these lazy objects Pin
Sarveshwar Mabrukhane15-Jun-14 20:11
memberSarveshwar Mabrukhane15-Jun-14 20:11 
GeneralVery simple and Understandable article Pin
MikeMTA27-Mar-14 7:01
memberMikeMTA27-Mar-14 7:01 
GeneralMy vote of 5 Pin
Renju Vinod6-Oct-13 19:26
professionalRenju Vinod6-Oct-13 19:26 
QuestionLazy, but not Weak. Pin
Paulo Zemek5-Oct-13 0:27
professionalPaulo Zemek5-Oct-13 0:27 
GeneralMy vote of 5 Pin
K K Kodoth4-Oct-13 19:20
professionalK K Kodoth4-Oct-13 19:20 
GeneralMy vote of 5 Pin
Joe Sonderegger25-Sep-13 2:42
memberJoe Sonderegger25-Sep-13 2:42 
GeneralMy vote of 5 Pin
Uday from Chennai22-Sep-13 6:53
memberUday from Chennai22-Sep-13 6:53 
GeneralMy vote of 5 Pin
Anthony Daly16-Sep-13 23:06
memberAnthony Daly16-Sep-13 23:06 
Questionif we need or do not need the address object Pin
Sakshi Smriti16-Sep-13 18:37
memberSakshi Smriti16-Sep-13 18:37 
AnswerRe: if we need or do not need the address object Pin
Shivprasad koirala16-Sep-13 18:46
mvpShivprasad koirala16-Sep-13 18:46 
GeneralRe: if we need or do not need the address object Pin
Sakshi Smriti16-Sep-13 18:50
memberSakshi Smriti16-Sep-13 18:50 
Suggestionpleasure Pin
xiaozhi_563816-Sep-13 16:35
memberxiaozhi_563816-Sep-13 16:35 
GeneralMy vote of 5 Pin
Prasad Khandekar14-Sep-13 6:30
professionalPrasad Khandekar14-Sep-13 6:30 
SuggestionNot bad, but needs more... PinPopular
Aron Weiler12-Sep-13 12:34
memberAron Weiler12-Sep-13 12:34 
GeneralMy Vote of 1 Pin
BCantor12-Sep-13 10:47
memberBCantor12-Sep-13 10:47 
AnswerRe: My Vote of 1 Pin
frblondin12-Sep-13 21:17
memberfrblondin12-Sep-13 21:17 
GeneralRe: My Vote of 1 Pin
Paw Jershauge12-Sep-13 22:21
professionalPaw Jershauge12-Sep-13 22:21 
GeneralRe: My Vote of 1 Pin
Rob Philpott19-Sep-13 2:56
professionalRob Philpott19-Sep-13 2:56 
GeneralMy vote of 4 PinPopular
Simon Gulliver12-Sep-13 6:27
memberSimon Gulliver12-Sep-13 6:27 
GeneralRe: My vote of 4 Pin
Shivprasad koirala12-Sep-13 6:34
mvpShivprasad koirala12-Sep-13 6:34 
GeneralRe: My vote of 4 Pin
Rob Philpott19-Sep-13 2:55
professionalRob Philpott19-Sep-13 2:55 
GeneralMy vote of 5 Pin
John Atten12-Sep-13 2:36
memberJohn Atten12-Sep-13 2:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160927.1 | Last Updated 17 Sep 2013
Article Copyright 2013 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid