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.
|