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


The big boss will not be happy with your work unless your work makes the client happy. This applies to load time of collection in the UI. If your app is taking more than expected time, client will not be happy. Today's post will help you to improve the performance of your application by lazy initialization of objects. - Article authored by Kunal Chowdhury on .

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.

Have a question? Or, a comment? Let's Discuss it below...

dhgate

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.