在IEnumerable扩展中 - 为什么只有Count()针对ICollection进行了优化?

Nit*_*kin 6 c# linq performance

在对Linq IEnumerable扩展方法进行反编译之后,我很高兴看到
Count()方法在尝试迭代整个可枚举之前尝试将其向下转换为ICollection或者ICollection<T>例如:

    public static int Count<TSource>(this IEnumerable<TSource> source) {

        if (source == null) throw Error.ArgumentNull("source");

        ICollection<TSource> collectionoft = source as ICollection<TSource>;

        if (collectionoft != null) return collectionoft.Count;

        ICollection collection = source as ICollection;

        if (collection != null) return collection.Count;

        int count = 0;

        using (IEnumerator<TSource> e = source.GetEnumerator()) {
            checked {
                while (e.MoveNext()) count++;
            }
        }
        return count;
    }
Run Code Online (Sandbox Code Playgroud)

为什么不发生这种情况Any()?它不会从使用.Count > 0而不是创建数组枚举器中受益吗?

Sri*_*vel 5

并非所有集合都提供O(1)Count属性访问权限.例如,访问计数属性ConcurrentQueue<T>是O(n).因此,优化会使情况变得更糟,因此不应将其称为优化.

不仅ConcurrentQueue<T>,几乎所有的并发集合(ConcurrentDictionary<TKey,TValue>,ConcurrentStack<T>等)属于这一类

可能这就是他们决定不这样做的原因.

  • @ChrisEelmaa不要密集.我的回答确实有道理.您的评论只是没有意义.问题是为什么没有为`Any`添加在`Count`方法中添加`ICollection`的优化.好的,你说`List <T>`.怎么样'数组'?,那么`ObservableCollection`怎么样?和所有收藏品?您想为每个语句添加if语句吗?优化应作为通用添加,而不是针对某些特定的具体类型. (2认同)