Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does foreach execute the query only once?

Tags:

I have a list of items and a LINQ query over them. Now, with LINQ's deferred execution, would a subsequent foreach loop execute the query only once or for each turn in the loop?

Given this example (Taken from Introduction to LINQ Queries (C#), on MSDN)

    // The Three Parts of a LINQ Query:      //  1. Data source.      int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };      // 2. Query creation.      // numQuery is an IEnumerable<int>      var numQuery =         from num in numbers         where (num % 2) == 0         select num;      // 3. Query execution.      foreach (int num in numQuery)     {         Console.Write("{0,1} ", num);     } 

Or, in other words, would there be any difference if I had:

    foreach (int num in numQuery.ToList()) 

And, would it matter, if the underlying data is not in an array, but in a Database?

like image 478
Marcel Avatar asked Nov 06 '12 11:11

Marcel


People also ask

What does a foreach loop do?

The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list. It executes for each element present in the array.

How long does a foreach loop take?

The foreach loop took 107 milliseconds to execute the same process while the classic for loop took 14 milliseconds.

Which is better foreach or LINQ?

LINQ syntax is typically less efficient than a foreach loop. It's good to be aware of any performance tradeoff that might occur when you use LINQ to improve the readability of your code.

Which is faster foreach or LINQ foreach?

No, LINQ iterators are not and will never be faster than foreach .


1 Answers

Now, with LINQ's deferred execution, would a subsequent foreach loop execute the query only once or for each turn in the loop?

Yes, once for the loop. Actually, it may execute the query less than once - you could abort the looping part way through and the (num % 2) == 0 test wouldn't be performed on any remaining items.

Or, in other words, would there be any difference if I had:

foreach (int num in numQuery.ToList()) 

Two differences:

  1. In the case above, ToList() wastes time and memory, because it first does the same thing as the initial foreach, builds a list from it, and then foreachs that list. The differences will be somewhere between trivial and preventing the code from ever working, depending on the size of the results.

  2. However, in the case where you are going to repeatedly do foreach on the same results, or otherwise use it repeatedly, the then while the foreach only runs the query once, the next foreach runs it again. If the query is expensive, then the ToList() approach (and storing that list) can be a massive saving.

like image 137
Jon Hanna Avatar answered Sep 30 '22 01:09

Jon Hanna