Let's say I have code like:
if (someEnumerable.Count() < 2) {
// Do something
}
Would this result in someEnumerable being iterated over fully, or would evaluation complete if Count() reaches a second item in the enumerable?
Let's say I have code like:
if (someEnumerable.Count() < 2) {
// Do something
}
Would this result in someEnumerable being iterated over fully, or would evaluation complete if Count() reaches a second item in the enumerable?
On
In general, the optimizations compilers do are quite conservative because they have to work for all cases.
From the compiler's point of view there are two discrete operations here. 1) counting the elements of the sequence represented by someEnumerable and 2) comparing that count to a specific value. The compiler has no way to know if there are any side effects of enumerating the sequence (I guess it could find out, but it gets hairy pretty quickly), so an optimization like this would change the semantics of someEnumerable.Count().
For what it is worth some implementations of Count can and do use properties if available, but that's controlled by the class implementing the interface and not in general by the compiler.
There is no compiler optimization regarding the behavior of methods. If at all that would be a runtime optimization of the method itself. But since
Enumerable.Countdoesn't know in which context it is used, it cannot change it's behavior.If you don't want to count something but just want to know if there is not more than one use:
However, if
someEnumerableis implementingICollection<TSource>orICollection(like arrays, lists or dictionaries) the method is optimized to simply use theCountproperty, so doesn't need to enumerate all items(source). Then it would be a micro optimization which hurts readability and i'd probably preferCount() < 2.