Visual Studio and .NET Framework Home
Enumerable.Count() is unnecessarily slow using a Covariant IEnumerable<T>
5/19/2009 3:01:48 PM
User(s) can reproduce this bug
Now that IEnumerable is covariant, some of the methods in Linq to Objects run slower than expected. For example. Count(). Count checks to see if the input implements ICollection<TSource> and if so, shortcuts and returns .Count. With a covariant IEnumerable though, it won't. The easy workaround is for Enumerable.Count() to also check for the non-generic ICollection and if so return Count there. As Count (and other similar methods, aren't type-specific, then it works.
.NET Framework 4 Beta 1
Operating System Language
Steps to Reproduce
Use code like the following:
List<ArgumentException> blah = new List<ArgumentException>();
IEnumerable<Exception> eblah = blah;
now do eblah.Count() -- using the System.Linq.Enumerable extension method.
The way the code inside Count() is written, it will try to check for ICollection<Exception> to short-circuit and return the count. Instead, it should also check for ICollection as Count does not depend on type.
I would expect that ICollection be used as the perf is much faster as it avoids an O(n) loop.
TAP Code (if applicable)
You can indicate your satisfaction with how Microsoft handled this issue by completing this quick
3 question survey
to post a comment.
Please enter a comment.
on 6/4/2009 at 4:50 PM
It does indeed check both :)
Visual C# Compiler Team
on 5/28/2009 at 8:50 PM
Long as it checks both ICollection<T> and ICollection as ICollection<T> does not derive from ICollection and some collections may not implement ICollection....wouldn't want to lose out on those ones either.
on 5/28/2009 at 6:00 PM
Nice catch, Oren. I've changed the Count optimization to use ICollection instead of ICollection<T>.
Development Manager, C# & VB compilers.
on 5/22/2009 at 3:50 AM
Thanks for your feedback.
We are escalating this issue to the appropriate group within the Visual Studio Product Team for triage and resolution.
These specialized experts will follow-up with your issue.
on 5/21/2009 at 4:16 AM
Thank you for your feedback, We are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com)
to post a workaround.
Please enter a workaround.
on 5/19/2009 at 3:02 PM
Write your own Count extension method and ensure it's resolved first.
© 2014 Microsoft