简体   繁体   中英

Do I need to check the Count() of an Enumerable before foreach

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 .

I don't believe there is any speed improvement or indeed point in checking the Count() of an Enumerable before iterating/foreaching over the collection. As no code is executed within the foreach block if there isn't any items in the collection anyway.

Short answer: No, on the contrary.
Longer answer: The foreach keyword calls methods on the IEnumerator interface. These methods implicitly check for items being present. So calling Count() is purely redundant.

即使你想检查计数,使用Count而不是扩展方法Count(),因为Count()的性能比Count更差

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM