反编译 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;
}
为什么这不会发生在 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/