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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With