a blog for those who code

Wednesday 14 October 2015

Lazy Loading in C#

In this post we will be discussing about lazy loading in C#. Lazy Loading actually means that we delay the loading of the object until we need it i.e. get the object when you need it. Lazy Loading is a design pattern which can contribute to efficiency of the program's operation if properly and appropriately used as per WikiPedia.

Lets take a simple example : 

public class Bird
{
  private string _Name; private List<Child> _Children = null;

  public Bird()
  {
     _Name = "Bird Name"; _Children = GetChildren();
  }
  private List<Child> GetChildren()
  {
     List<Child> children = new List<Child>();
     Child child = new Child(); child.Name = "1st Child";
     children.Add(child);
     child = new Child(); child.Name = "2nd Child";
     children.Add(child);
     return children;
  }
}
public class Child
{
   public string Name;
}

In the above example we have two classes Bird and Child where Bird class has many Child objects in it. In the constructor of Bird objects we are calling GetChildren() to load all the Child objects of Bird Class. So when the Bird object is created it will load all the children, so even if we do not need the children of particular bird our code will load it.

How to implement Lazy Loading in the above code 

To implement lazy loading we will remove the loading of Child objects from the Bird constructor. It will be only loaded when you need it.

public Bird()
{
  _Name = "Bird Name"; //_Children = GetChildren();
}
public List<Child> Children
{
  get
  {
    if(_Children == null)
    {
      _Children = GetChildren();
    }
    return _Children;
  }
}

Now this way the Child Objects will not be loaded until you call the Children property of Bird class.

Along with this we have a Lazy<T> class in C# which provides the support for lazy loading as shown below.


The advantages of Lazy Loading over Eager Loading are :

1. Lazy loading reduces your application start-up time.
2. It saves memory by only loading what is needed

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment