Tuesday, October 4, 2011

Deferred Execution or Lazy Execution in LINQ

MSDN definition: 

Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. Deferred execution can greatly improve performance when you have to manipulate large data collections, especially in programs that contain a series of chained queries or manipulations.

Most of the query operators in Linq executes not when they are constructed but when enumerated.

Following example can help in explaining the Deferred execution in LINQ queries:-

List<string> lNames= new List<string>();
lNames.Add("Steve");
IEnumerable<string> strLoop = lNames.Select(n => string.Concat("Hello " + n)); lNames.Add("Mark");
foreach (string n in strLoop)
{
     Console.WriteLine(n);
}


Output of the query
-------------------
Hello Steve
Hello Mark

As it can be seen in the output of the query, the string “Mark” was added later after the construction of the query but still its included in the output. This is called as Deferred or Lazy execution. 

Most of the query operators provides deferred execution mode except the following ones:-
a)      operators that return a single element. Ex: Count etc.

b)      Conversion operators. Ex: ToList, ToArray etc.


No comments :

Post a Comment