Jux
Jux

Reputation: 1

Loop performance with LINQ clause

is there any performance difference between both ? In my opinion, the second method is slower because linq must re-execute the where clause to each iteration, is that right ?

Thanks :)

List<string> someObjects = new List<string>() { "one", "two" };

var filteredCollection = someObjects.Where(s => s.Contains('w'));

foreach (string str in filteredCollection)
{
    // some code
}
List<string> someObjects = new List<string>() { "one", "two" };

foreach (string str in someObjects.Where(s => s.Contains('w')))
{
    // some code
}

Upvotes: 0

Views: 210

Answers (1)

Gus Lindell
Gus Lindell

Reputation: 346

foreach is a bit of syntax sugar:

foreach(string str in someObjects.Where(s => s.Contains('w'))) 
{
   // some code (using str)
}

would be expanded by the compiler to something like

IEnumerator<string> iterator = someObjects.Where(s => s.Contains('w')).GetEnumerator();
while(iterator.MoveNext())
{
    // some code (using iterator.Current)
}

The Where() extension method is only called once at the beginning to create the iterator.

Upvotes: 3

Related Questions