Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq deferred operations

Tags:

c#

.net

linq

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

like image 570
haughtonomous Avatar asked Sep 04 '13 14:09

haughtonomous


People also ask

What is LINQ deferred execution?

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.

What are the benefits of a deferred execution in LINQ?

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.

What are the deferred execution and the immediate execution in LINQ?

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.

What construct does LINQ use to offer deferred execution?

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.


1 Answers

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
like image 159
Sergey Berezovskiy Avatar answered Sep 22 '22 14:09

Sergey Berezovskiy