Deferred Execution vs Immediate Execution in LINQ


LINQ provides two different behaviors of Query Execution –

  • Deferred Execution 
  • Immediate Execution
Deferred/Lazy Operators Immediate/Greedy Operators
 Query is not executed at the point of its declaration.  Query is executed at the point of its declaration.
Projection Operator – Select, SelectMany
Restriction Operator – WherePaging Operator – Take, Skip
Aggregate Functions – Count, Average, Min, Max, Sum
Element Operators – First, Last, SingleToList, ToArray, ToDictionary

Deferred Execution 

By default, LINQ uses deferred execution.

When we write a LINQ query, it doesn’t execute by itself. It executes, when we access the query results.In other words, execution of the query is deferred until the query variable is iterated over in a foreach loop.

Benefits of Deferred Execution

  • It avoids unnecessary query execution and hence improves performance.
  • Query construction and Query execution are decoupled, so we can create the LINQ query in several steps.
  • A deferred execution query is reevaluated when you re-enumerate – hence we always get the latest data.
DeferredExecution

Deferred Execution Example

 

In the above example, we first create a list of 3 Employees. We then construct the LINQ Query. Once done, we create a new instance of the Employee object.

Now had the query been executed when the LINQ Query was constructed, the result would have been only ‘Samir’. However that is not the right result in this case.

The Output of the program is Samir, Mark

This is because the execution of the query was deferred until the query variable was iterated using a foreach loop.

Immediate Execution

Immediate execution is the reverse of deferred execution. It forces the LINQ query to execute and gets the result immediately.

 

To force immediate execution of a query, that return a singleton value, we can use the aggregate operators or element operators.

To force immediate execution of a query that does not produce a singleton value, we can call the ToList method, the ToDictionary method, or the ToArray method on a query or query variable.

ImmediateExecution

Immediate Execution Example

The Output of the above program is only ‘Samir’

This is because the execution of the query was done immediately, when it was constructed – since we used the ‘ToList’ operator. 

 



Categories: C#, LINQ

3 replies

  1. Nice article

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: