3
foreach(Value v in myDictionary[key])

In this scenario, is the compiler able to determine that myDictionary[key] will always be the same and not hash the [key] every iteration of foreach?

foreach(Value v in myEnumerable.Where(s => s.IsTrue))

I know enumerables are lazy, I suspect that in this case, the .Where only resolves once and returns a full collection for the foreach but that is only a hunch.

Judging by this question, the foreach is doing a .GetEnumerable even in scenario 1, so its the return of that which is used so therefore it only resolves once and not on every iteration.

Community
  • 1
  • 1
user99999991
  • 1,351
  • 3
  • 19
  • 43

1 Answers1

4

foreach in C# is just a syntactic sugar.

foreach (V v in x) embedded-statement

gets expanded into

{
    E e = ((C)(x)).GetEnumerator();
    try {
        while (e.MoveNext()) {
            V v = (V)(T)e.Current;
            embedded-statement
        }
    }
    finally {
        … // Dispose e
    }
}

As you can see, x is only used once, to get the enumerator by calling GetEnumerator on it. So your dictionary lookup will only be executed once. Later on it does only care about that enumerator, not where it came from.

Community
  • 1
  • 1
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263