In .NET, is it better to call .Count() or, when available, .Count?
When the Linq namespace is imported, it is possible to use both .Count() and .Count (on objects that implement IList for example).
.Count() will call the .Count property, if available, as per: C# Count() Extension Method Performance
Is it better then to directly use .Count over .Count(), for a (small) pe开发者_如何学Crformance gain?
Update: interesting performance figures here (1-2 orders of magnitude): Is the Linq Count() faster or slower than List.Count or Array.Length?
My personal preference is to stick with the existing methods and properties if they are available without casting. Therefore I'd use Count
.
The performance will be the same, as the Count()
extension methods checks wether it is an ICollection
and uses the Count
property if it is (this is for the .net linq stack).
Reference: msdn (Remarks)
I use .Count when I don't want to filter a count, then use the Query Extension when I do want a filtered count.
Most likely .Count is better when it is available. However, you don't know if .Count is a property that is derived from a function upon accession.
Since .Count is most likely predetermined before you call it, it should be more efficient if the previous isn't the case.
精彩评论