Do I need to check the enumeration Count () before foreach

Is there any speed improvement or does it really point to checking the Count() Enumerable before iterating / deleting over the collection?

 List<int> numbers = new List<int>(); if(numbers.Count() > 0) { foreach(var i in numbers) {/*Do something*/} } 
+7
c #
source share
5 answers

No, maybe the other way around. If it is not a collection (such as List or Array ), but a pending executed query, it must be executed completely, which can be very expensive, just to determine the counter. In your example, this is actually List , Enumerable.Count smart enough to first transfer it to ICollection<T> / ICollection . If this succeeds, the Count property is used.

So just use foreach . It doesn’t hurt if the sequence is empty, the cycle will be immediately deleted.

For the same reason, it is better to use Enumerable.Any instead of Count() > 0 if you just want to check if the sequence contains at least one element. The goal is also more clear.

+17
source share

If your Enumarable is lazy (LINQ), calling Count() is actually very bad, as it computes the entire Enumerable.

Since foreach fails if Enumarable is empty, it is best not to use Count .

+2
source share

I do not believe that there are any speed improvements or it really is worth checking the Count() Enumerable before iterating / moving through the collection. Since no code is executed in the foreach block if there are no elements in the collection.

+1
source share

Short answer: No, vice versa.
Longer answer: foreach methods on the IEnumerator interface. These methods implicitly check for elements. Therefore, calling Count() is purely redundant.

+1
source share

Even if you want to check the counter, use Count instead of the Count () extension method, since Count () performance is worse than Count

0
source share

All Articles