I often write code like this:
if ( list.Count > 0 ) { }
Is this efficient? Does this operation look like:
- Iterate through the list and count its elements
- Result: 986,000 elements
- Is 986,000 greater than 0?
- return true
Or like this:
- Retrieve the stored number of elements in the list (986,000)
- Is 986,000 greater than 0?
- return true
That is, to get the number of elements in the list, do you have to count all the way through the list, or is the number of elements recorded somewhere? And is this the case for all ICollection classes?
What about the Capacity of the list?
Yes. That retrieves the count in the list, which is stored in a field inside the list, and compares it to zero.
Now a question you did not ask:
We interrogate the sequence at runtime to see if it is a list that has a
Countproperty that can be computed efficiently. If it does, we call it. If not, we count the entire sequence one item at a time, and then compare that to zero.Yes.
if (sequence.Any())Because it attempts to iterate over one element. If it succeeds, then
Anyis true; if it fails thenAnyis false. You don’t need to count the number of jellybeans in the jar in order to know if there are more than zero. You only need to look to see if there is at least one.In addition to being considerably more efficient, the code now reads like the intended meaning of the code. If you are intending to ask “are there any items in the list?” then ask “are there any items in the list?” and not “is the number of items in the list greater than zero?”
That tells you how much space has been pre-allocated in the list’s internal data structures. It is the amount of items the list can store before it has to allocate more memory.