Is there any speed improvement or indeed point in checking the Count() of an Enumerable before iterating/foreaching over the collection?
List<int> numbers = new List<int>();
if(numbers.Count() > 0)
{
foreach(var i in numbers) {/*Do something*/}
}
No, the opposite can be true. If it's not a collection (like a List or Array) but a deferred executed query it must be executed completely which can be very expensive, just to determine the count. In your example it's actually a List, Enumerable.Count is clever enough to try to cast it to a ICollection<T>/ICollection first . If that succeeds the Count property is used.
So just use the foreach. It doesn't hurt if the sequence is empty, the loop will be exited immediately.
For the same reason it's better to use Enumerable.Any instead of Count() > 0 if you just want to check if a sequence contains at least one element. The intention is also more clear.
If your Enumarable is lazy evaluated (LINQ) the call to Count() is actually very bad since it evaluates the whole Enumerable.
Since foreach doesn't execute if the Enumarable is empty it's best to not use Count.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With