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

标签 c# performance linq

反编译 Linq 后 IEnumerable扩展方法我很高兴看到
Count()方法,在尝试迭代整个可枚举之前,尝试将其向下转换为 ICollectionICollection<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;
    }

为什么这不会发生在 Any() 中? ?使用 .Count > 0 不会有好处吗?而不是创建数组枚举器?

最佳答案

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

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

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

关于c# - 在 IEnumerable 扩展中 - 为什么只有 Count() 针对 ICollection 进行了优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26236896/

相关文章:

c# - 在子列表中传递带有过滤器/组的对象

iphone - 在 UIView 中逐步绘制 (iPhone)

c# - LINQ to 对象过滤

c# - 尽管有 Distinct(),LINQ 查询仍返回重复项

c# - 为什么此 Linq 不起作用(将 Linq 表达式翻译为 URI : Can only specify query options (orderby, 时出错,其中,采取,跳过)

c# - 如何知道一个类的最低基数是某种类型

c# - 一行代码创建一个只有一个条目的字典

c# - 将 appsetting 值从字符串解析为字符串数组

performance - Apache是​​否缓存静态文件的压缩版本?

java - ChronicleMap 和 parallelStream