Search code examples
c#clrcompiler-optimizationcil

Is the C# compiler able to optimize a statement like someEnumerable.Count() < 2?


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?


Solution

  • 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.Count doesn'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:

    if (!someEnumerable.Skip(1).Any()) {
       // Do something
    }
    

    However, if someEnumerable is implementing ICollection<TSource> or ICollection(like arrays, lists or dictionaries) the method is optimized to simply use the Count property, so doesn't need to enumerate all items(source). Then it would be a micro optimization which hurts readability and i'd probably prefer Count() < 2.