What is Lazy loading and how this will benefit your project?


Let’s suppose you built an application which loads records in a Grid in a paginated manner. But when you loaded thousands of records, you noticed that, it is taking more time to load than the expected time and your boss was not happy with that.

 

So, what to do? Are there any kind of proper solutions or workarounds to reduce this load time? If so, what are those? Let’s began with our post with a problem statement.

 

Problem Statement

It was the old days when we had a slower machine configurations where the processing was too slow but as the computing system progresses, our need increases. Now we need faster, faster and more faster processor, we need slowest loading times when we work on a collection of data. The demand is getting increases day by day and there is no end to that. It’s a mind set of all human being. If people gets something better, he needs more and more, just like an ocean.

 

The same thing happens to our applications too. You can not make your user happy with what you build. Everyone needs more faster output from that. Let’s suppose you have a DataGrid (I am not mentioning here any kind of Technology as it is less or more same in all technical fields) and fetching thousands of records and adding them to it but while displaying, you are just showing 10 or 20 records using the Data Pager.

 

You noticed that, it is having a load time issue than the expected and your boss was not happy with that. We needs 1/10th of what is currently available. So, what to do to reduce this loading time?

 

Faster Loading Graph

 

Everything has it’s own solution. You can fetch no. of records that you need to show in the DataGrid and on click of next, you can have another round trip to the server to fetch another set of data. You discussed the same with your boss but he was not happy on that too. It pushed you to a deep thinking. The reason behind this is, it will increase the server round trip and the users have to wait every time when the user clicks on next or previous record set.

 

Again, what to do? Ok, to help you on this I will ask you one question. Have you heard about the word “Lazy Loading”? What is that? How this will help you? Let’s have the discussion on this topic today

 

Lazy Initialization… Your Friend!

If you are using Microsoft .NET 4.0 or higher, it comes with an excellent feature called Lazy Initialization. .NET 4.0 introduces a “Lazy<T>” class to support the lazy initialization, where “T” specifies the type of object that is being initialized lazily. This is a new feature of C# 4.0 and can be used when we are working with large objects.

 

To learn more about it, let’s create a Console application first and then create a class named “Person”. Now create a custom constructor that takes a parameter “id” as integer. In the constructor implementation, write a line to the console as “Constructor of Person <ID> has been called”. Here is the code for your reference:

 

public class Person
{
    public Person(int id)
    {
        Console.WriteLine("Constructor of Person " + id + " has been called");
    }
}

 

Now, as per default implementation, it will print the line every time when you create an instance of the class. Right? Don’t go with my words. Let’s see that in action. Let us create an array of six Person and then get the instance of the 3rd person from that collection. Need the code? Here it is for you:

 

class Program
{
    static void Main(string[] args)
    {
        var persons = new[]
        {
            new Person(1),
            new Person(2),
            new Person(3),
            new Person(4),
            new Person(5),
            new Person(6),
        };
 
        var person = persons[2]; // this will return the instance of Person 3
        Console.ReadLine();  // just to make sure that the application halts here
    }
}

 

As per the default behaviour, it will print six lines in the console screen. Each line represents creation of a single instance. You can check the ID to cross check it. The output will look similar to this as per our code:

 

Lazy Loading Demo

 

So, think about the thousands of records! This will create instances of those many records in the memory unnecessarily without any need. User might not go to the end of the collection but the instances of the object is ready. Maximum time this creates issues in WPF, Silverlight DataGrid or List.

 

Now, let us modify our existing code and build the lazy initialization to it. Now instead of a Person array, we will create an array of type Lazy<Person>, that’s all! The implementation step is as shown below:

 

class Program
{
    static void Main(string[] args)
    {
        var persons = new[]
        {
            new Lazy<Person>(() => new Person(1)),
            new Lazy<Person>(() => new Person(2)),
            new Lazy<Person>(() => new Person(3)),
            new Lazy<Person>(() => new Person(4)),
            new Lazy<Person>(() => new Person(5)),
            new Lazy<Person>(() => new Person(6)),
        };
 
        var person = persons[2].Value; // this will return the instance of Person 3
        Console.ReadLine();  // just to make sure that the application halts here
    }
}

 

If you need to fetch the 3rd person only, get it from “Value” property of the item from the array collection. So, to get the instance of person with ID=3, call person[2].Value, this will return the instance of Person 3.

 

Let’s run the code this time. Voila! It just called only the constructor of Person 3 this time. That means, it created the instance of person 3 when we actually used it. The other instances in the array have not been created yet. So, if we call any other instance, at that time only it will create that particular instance. Check out the below screenshot:

 

Default Loading

 

Isn’t it fine? Will not it save lot’s of processing and memory when your application runs? This feature is called as “Lazy Initialization” or “Lazy Loading”. If you heard about it just now, let’s go and ask your boss additional time to do a POC in your actual project. I hope, he will be happy after this.

 

Was this post helpful? Don’t forget to leave your comment below and if you have any queries, please drop a line below and I will try to respond you as soon as I can. You can always connect with me on Twitter or Facebook for a quick chat. Feedbacks are always welcome as this will help me to improve my posts in future and help you in a better way.


27 comments

  1. Good feature in 4.0
    Nice explained!!!

    ReplyDelete
  2. Good feature in 4.0
    Nice explained!!!

    ReplyDelete
  3. how we can use it in gridview ? any example or sample code ?

    ReplyDelete
  4. Replies
    1. Thank you Michael for the feedback. Please read tomorrows blog post. You will like that.

      Delete
  5. Thank you Kunal for the blog post. Useful information which I bookmarked and shared to my team members to implement in our project.

    ReplyDelete
    Replies
    1. Thank you Puja for the recommendation. Highly appreciable. Thanks.

      Delete
  6. Wow this is excellent... Nice Tip kunal to impress my Boss :)

    ReplyDelete
    Replies
    1. Thanks Bhuvan. All the best for impressing your boss ;)

      Delete
  7. Nice starter but it would be nice to see how this technique would actually save roundtrips to the database (which was the initial argument of this article)...

    ReplyDelete
    Replies
    1. It will only save your roundtrip to server if you bring all the collection at once which might not be good in all cases.

      Delete
  8. Very Usefull tip Kunal, Thnx.

    ReplyDelete
    Replies
    1. Glad to know that, you liked it. Thanks for your feedback Santhosh.

      Delete
  9. very nice explanation..
    and thanks

    ReplyDelete
    Replies
    1. Thanks ABY for your feedback. I hope, it will be helpful for you.

      Delete
  10. Thanks! I had heard of it but now I know what it is.

    ReplyDelete
  11. Thanks sir,,, I share your useful post with my classmate.
    joginder

    ReplyDelete
  12. Awesome Thinking sir.... How did you get this idea !

    ReplyDelete
  13. I think you should fulfill this item with the issue of WHEN NOT TO USE LAZY LOADING,as
    Microsoft Certified Trainer Wesley Bakker explains:
    http://weblogs.asp.net/wesleybakker/archive/2009/07/27/deadly-poison-of-lazy-loading-and-not-following-design-guidelines.aspx

    ReplyDelete


 
© 2008-2014 Kunal-Chowdhury.com | Designed by Kunal Chowdhury
Back to top