更新时间:2022-04-27 15:21:13
的IEnumerable< T>
一般是在这里一个更好的选择,因为在其他地方上市的原因。不过,我想提出关于一个点计数()
。昆廷是不正确时,他说该类型自身实现计数()
。它在 Enumerable.Count实际执行的()
作为一个扩展方法,这意味着其他类型没有得到覆盖它,以提供更有效的实现。
IEnumerable<T>
is generally a better choice here, for the reasons listed elsewhere. However, I want to bring up one point about Count()
. Quintin is incorrect when he says that the type itself implements Count()
. It's actually implemented in Enumerable.Count()
as an extension method, which means other types don't get to override it to provide more efficient implementations.
在默认情况下,计数()
必须遍历整个序列来计算的项目。然而,它的确实的了解的ICollection&LT; T&GT;
和的ICollection
,并进行了优化这些情况。 (; T&gt;以.NET 3.5 IIRC它只是为的ICollection&LT优化
)现在数组的确实的实施,使 Enumerable.Count()
推迟到的ICollection&LT; T&GT; .Count之间
并避免遍历整个序列。它仍然会比调用长度
直接,因为计数()
有发现,它实现了的ICollection&LT; T&GT; 来开始 - 但至少它仍然是O(1)
By default, Count()
has to iterate over the whole sequence to count the items. However, it does know about ICollection<T>
and ICollection
, and is optimised for those cases. (In .NET 3.5 IIRC it's only optimised for ICollection<T>
.) Now the array does implement that, so Enumerable.Count()
defers to ICollection<T>.Count
and avoids iterating over the whole sequence. It's still going to be slightly slower than calling Length
directly, because Count()
has to discover that it implements ICollection<T>
to start with - but at least it's still O(1).
同样的事情是性能一般情况:遍历数组,而不是一般的顺序时,即时编译code可能是有点紧张。你基本上可以给JIT的更多信息一起玩,甚至是C#编译器本身不同的对待数组迭代(直接使用索引)。
The same kind of thing is true for performance in general: the JITted code may well be somewhat tighter when iterating over an array rather than a general sequence. You'd basically be giving the JIT more information to play with, and even the C# compiler itself treats arrays differently for iteration (using the indexer directly).
然而,这些性能上的差异将是微不足道的的最的应用程序 - 我肯定会与更通用的接口去,直到我有很好的理由不
However, these performance differences are going to be inconsequential for most applications - I'd definitely go with the more general interface until I had good reason not to.