When does foreach resolve the container?
foreach(Value v in myDictionary[key])
In this case, the compiler can determine that myDictionary [key] will always be the same, and not hash [key] on each iteration of foreach?
foreach(Value v in myEnumerable.Where(s => s.IsTrue))
I know enums are lazy, I suspect in this case .Where only allows once and returns the full collection of foreach, but that's just a guess.
Judging from this question, foreach does .GetEnumerable even in scenario 1, so its returning what is used, so it only allows it once and not on every iteration.
source to share
foreach
in C # is just syntactic sugar .
foreach (V v in x) embedded-statement
expanding 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, it x
is only used once to get the enumerator by calling on it GetEnumerator
. This way, the dictionary lookup will only be done once. Later, he only cares about that enumerator, not where it came from.
source to share