gpt4 book ai didi

c# - Linq 计数与 IList 计数

转载 作者:太空宇宙 更新时间:2023-11-03 19:04:40 25 4
gpt4 key购买 nike

如果我有以下来自某个存储库的 IEnumerable 列表。

IEnumerable<SomeObject> items = _someRepo.GetAll();

什么更快:

items.Count(); // Using Linq on the IEnumerable interface.

List<SomeObject> temp = items.ToList<SomeObject>(); // Cast as a List

temp.Count(); // Do a count on a list

Linq Count() 比将 IEnumerable 转换为 List 然后执行更快还是更慢Count()?

更新:将问题稍微改进为更现实的场景。

最佳答案

调用 Count直接是更好的选择。

Enumerable.Count内置了一些性能改进,可以让它在不枚举整个集合的情况下返回:

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;
}

ToList()使用类似的优化,融入 List<T>(IEnumerable<T> source)构造函数:

public List(IEnumerable<T> collection) {
if (collection==null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
Contract.EndContractBlock();

ICollection<T> c = collection as ICollection<T>;
if( c != null) {
int count = c.Count;
if (count == 0)
{
_items = _emptyArray;
}
else {
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
else {
_size = 0;
_items = _emptyArray;
// This enumerable could be empty. Let Add allocate a new array, if needed.
// Note it will also go to _defaultCapacity first, not 1, then 2, etc.

using(IEnumerator<T> en = collection.GetEnumerator()) {
while(en.MoveNext()) {
Add(en.Current);
}
}
}
}

但如您所见,它只使用通用的 ICollection<T> , 所以如果你的收藏实现了 ICollection但不是它的通用版本调用 Count()直接会快很多。

不打电话 ToList first 还为您节省了新的分配 List<T> instance - 不是太昂贵的东西,但最好尽可能避免不必要的分配。

关于c# - Linq 计数与 IList 计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30225639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com