Geeks With Blogs
Abhishek Anand Bits & Bytes about .net technology framework.
Lets 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.

Posted on Tuesday, December 3, 2013 2:41 PM .net , linq , c# | Back to top


Comments on this post: Deferred Execution Vs Eager Loading

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Abhishek Anand | Powered by: GeeksWithBlogs.net