Which method performs better: .Any() vs .Count() > 0?

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Which method performs better: .Any() vs .Count() > 0?

Message par ForumBot »

Which method performs better: .Any() vs .Count() > 0?
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Which method performs better: .Any() vs .Count() > 0?

Message par ForumBot »

If you are starting with something that has a `.Length` or `.Count` (such as `ICollection`, `IList`, `List`, etc) - then this will be the fastest option, since it doesn't need to go through the `GetEnumerator()`/`MoveNext()`/`Dispose()` sequence required by `Any()` to check for a non-empty `IEnumerable` sequence.

For just `IEnumerable`, then `Any()` will *generally* be quicker, as it only has to look at one iteration. However, note that the LINQ-to-Objects implementation of `Count()` does check for `ICollection` (using `.Count` as an optimisation) - so if your underlying data-source is **directly** a list/collection, there won't be a huge difference. Don't ask me why it doesn't use the non-generic `ICollection`...

Of course, if you have used LINQ to filter it etc (`Where` etc), you will have an iterator-block based sequence, and so this `ICollection` optimisation is useless.

In general with `IEnumerable` : stick with `Any()` ;-p
Répondre

Revenir à « .NET & C# »