Joh*_*sch 3 c# performance ienumerable count
考虑以下代码:
static IEnumerable<int> GetItems()
{
return Enumerable.Range(1, 10000000).ToArray(); // or: .ToList();
}
static void Main()
{
int count = GetItems().Count();
}
Run Code Online (Sandbox Code Playgroud)
它会迭代所有 100 亿个整数并一一计数,还是会使用数组Length/列表的Count属性?
如果IEnumerable是ICollection,它将返回该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;
}
Run Code Online (Sandbox Code Playgroud)
数组实现了ICollection<T>,因此不需要枚举。