I mostly understand deferred execution, but I have a question about a particular case:
Given a code fragment such as
var resultsOfInterest = from r in ...
select r;
foreach (var x in resultsOfInterest)
{
//do something with x
}
how many times is the query resultsOfInterest executed? Once when setting up the foreach loop, or once for every element 'x'? Would it be more efficient with
foreach (var x in resultsOfInterest.ToArray())
{
//do something with x
}
?
TIA
Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. It greatly improves performance by avoiding unnecessary execution.
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.
The basic difference between a Deferred execution vs Immediate execution is that Deferred execution of queries produce a sequence of values, whereas Immediate execution of queries return a singleton value and is executed immediately.
Example: Use the yield return construct in an extension method to defer execution. The following example shows the order of execution when using an extension method that uses deferred execution. The example declares an array of three strings.
It will be executed once, jut before loop, when GetEnumerator()
method will be executed over query variable. Here is how foreach loop looks like:
var enumerator = resultsOfInterest.GetEnumerator(); // query executed here
while(enumerator.MoveNext()) // iterating over results of query execution
{
var x = enumerator.Current;
// do something with x
}
Second sample will not be more efficient, it simply stores results of query execution in array, and then calls array iterator:
var enumerator = resultsOfInterest.ToArray().GetEnumerator();
// loop stays same
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With