As John Skeet says, both methods will essentially have to do the same thing - enumerate the sequence, conditionally increasing the counter when the predicate coincides. Any differences in performance between them should be small: minor for almost all use cases. If there is a marker winner, I think that it should be the first, since from the reflector it seems that the Count overload, which uses the predicate, uses its own foreach to list, and not for the more obvious way of unloading, working with a Where stream without Count parameters, as in your second example. This means that Technique No. 1 probably has two minor advantages:
- Checks fewer argument checks (null tests, etc.). Technique No. 2
Count also checks if its (tubular) input is ICollection or ICollection<T> , which it cannot be. - One configured enumerator against two counters connected together (an additional state machine has costs).
There is one minor argument in favor of method # 2, though: Where little harder to build an enumerator for the source sequence; it uses another for lists and arrays. This can make it more effective in certain scenarios.
Of course, I have to repeat that I could be wrong in my analysis - reasoning about performance using static code analysis, especially when the differences are likely to be insignificant, is not a good idea. There is only one way to find out - measuring runtime for your particular setup.
FYI, the source I thought of was from .NET 3.5 SP1.
source share