February 13, 2014

Lazy Loading Vs Eager Loading in LINQ

In Entity Framework, we have two types of loading available. Lazy Loading and Eager Loading. Both types of loading is related to database hits in an application that can effect the performance of application. 

In Lazy Loading, we load the parent table data only.

In Eager Loading, when we load the parent table data, at the same time we also get the data from its related table (child table).

Let's start with an example:

int[] listOfNumbers = new int[] { 5, 9, 8, 1, 7, 3, 6, 4, 2, 0 }; 
       int i = 0;
       var query = from num in listOfNumbers select ++i;
       // Note, the local variable 'i' is not incremented until each element is evaluated (as a side-effect):
       foreach (var x in query)
       {
           Console.WriteLine("x = {0}, i = {1}", x, i);
       }
Now without deferred execution we would expect that after the variable “query” is declared, “i” would have the value 10 and the output would be: “x = {1-10}, i = 10”  However since the LINQ statement is lazy loaded, the “++i” is not evaluated until each element is requested by the for each loop. Thus, the output instead is: 
x = 1, i = 1
x = 2, i = 2
x = 3, i = 3
x = 4, i = 4
x = 5, i = 5
x = 6, i = 6
x = 7, i = 7
x = 8, i = 8
x = 9, i = 9
x = 10, i = 10
Eager Loading :
int[] listOfNumbers new int[] { 5, 9, 8, 1, 7, 3, 6, 4, 2, 0 };
        int i = 0;
        var query = (from num in listOfNumbers select ++i).ToList();
        foreach (var x in query)
        {
            Console.WriteLine("x = {0}, i = {1}", v, i);
 }
 Output:
v = 1, i = 10
v = 2, i = 10
v = 3, i = 10
v = 4, i = 10
v = 5, i = 10
v = 6, i = 10
v = 7, i = 10
v = 8, i = 10
v = 9, i = 10
v = 10, i = 10

As we can see, with eager loading “++i” is evaluated during the declaration of “query” and “i” is equal to 10 for the entire duration of the output.

1 comment: