我声明了这个数组:
int[] misInts = new Int[someNumber];
/* make some happy operations with the elements in misInts */
Run Code Online (Sandbox Code Playgroud)
所以我可以得到SomeNumber的值:misInts.Length或misInts.Count()
C#中的数组继承自IEnumerable.所以,如果我有:
Func<int> misIntsF = Enumerable.Range(0, someNumber).Select(c=> /* make some happy operations that return Integers */);
Run Code Online (Sandbox Code Playgroud)
我被告知,如果我创建misIntsF.Count(),我实际上执行Lambda表达式中的代码,获取结果并计算它们.但阵列misInts没有Lambda表达.
是misInts.Count()比misInts更多的内存消耗.Length?misInts.Count()和misInts.Length之间有什么区别?
SLa*_*aks 25
array.Count()
实际上是对Enumerable.Count<T>(IEnumerable<T>)
扩展方法的调用.
由于此方法采用IEnumerable<T>
(而不是ICollection<T>
具有Count
属性),因此需要遍历整个序列以确定其大小.
但是,它实际上检查参数是否实现ICollection<T>
(哪个数组执行),如果是,则Count
直接返回.
因此,调用.Count()
数组并不比.Length
它慢得多,尽管它会涉及额外的类型转换.
因为Enumerable.Count
首先看它是否可以施放,所以 没有太大的区别ICollection<T>
.
MSDN:
如果源的类型实现ICollection,则该实现用于获取元素的数量.否则,此方法确定计数.
资源:
ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null)
{
return collection.Count;
}
Run Code Online (Sandbox Code Playgroud)
否则它将枚举序列来计算它:
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
Run Code Online (Sandbox Code Playgroud)
(来源:ILSpy)
归档时间: |
|
查看次数: |
8877 次 |
最近记录: |