0

I am cleaning the old code and found following Dynamic Loop.

foreach (var obj in listValues.Where(x => x.Valid == false))
{
}

I have a question that, the performance will be increase of following code as compare to above loop?

var myList = listValues.Where(x => x.Valid == false);
foreach (var obj in myList)
{
}
Ob Ahmed
  • 3
  • 3
  • 1
    I doubt if it will be any difference in performance: the optimizer is smart enough to add / remove local variable (`myList`) – Dmitry Bychenko Jun 24 '22 at 11:29
  • It is exactly the same. Why would there be a difference? (Remark: If the type of `.Valid` is a plain `bool` (and not a nullable, `bool?`, or something), then most people prefer writing `(x => !x.Valid)` instead, but this is for stylistic reasons, not because of performance.) PS! This is not considered "dynamic". The `Where` method gives a so-called iterator that functions lazily (deferred execution). – Jeppe Stig Nielsen Jun 24 '22 at 12:10

1 Answers1

2

Moving the listValues.Where(x => x.Valid == false) to the variable will not increase the performance the loop. foreach is actually compiled into while loop with result of listValues.Where(x => x.Valid == false).GetEnumerator() stored in separate variable. Something like next:

    IEnumerator<int> enumerator = listValues.Where(...).GetEnumerator();
    try
    {
        while (enumerator.MoveNext())
        {
            int current = enumerator.Current;
        }
    }
    finally
    {
        if (enumerator != null)
        {
            enumerator.Dispose();
        }
    }

So no additional enumerations should happen (if that is your concern).

Guru Stron
  • 102,774
  • 10
  • 95
  • 132