This article is a mirror article of machine translation, please click here to jump to the original article.

View: 22799|Reply: 1

[Source] Linq: Never use Count() > 0 to determine that the set is non-empty

[Copy link]
Posted on 10/12/2017 1:25:01 PM | | | |
Before Linq, we usually used the following method to determine whether a collection is non-empty, i.e., a collection contains elements:


Using the Length or Count attribute, there is no problem with the above writing.

But in the Linq era, the Enumerable.Count extension method "unified" the Length and Count properties, resulting in the following way of writing to judge non-nullity:


This writing is fine and works fine, but it can cause very serious performance issues.

Note that it is possible, not necessarily, and if the above method is passed in as an Array<T>, List, or Collection<T>, there will be no problem.



So when will something go wrong? Let's look at the following methods:


When called:



The execution speed will be quite slow, and it took about 70 seconds for my computer to execute the source. Count() > 0。


If you analyze it, you will find that the yield return i in line 5 of the GetNums code executes int. MaxValue, is it necessary?

In fact, as long as we return one element, we can conclude that the set is non-empty, and there is no need to return all the elements at all.

So how to judge? We can use the Enumerable.Any extension method:



Modify the SomeAction method as follows:



Call it again and you'll find that the execution time is negligible.


To sum up, Count() > 0 will inevitably have performance problems when it encounters yeild return.






Previous:C# implementation of three timers
Next:js string to date and date plus day
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com