IEnumerable的< T> VS T [] [英] IEnumerable<T> vs T[]

查看:130
本文介绍了IEnumerable的< T> VS T []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚意识到也许我是错在揭露所有的时间 T [] 我的意见,而不是的IEnumerable< T>

I just realize that maybe I was mistaken all the time in exposing T[] to my views, instead of IEnumerable<T>.

通常情况下,这类code的:

Usually, for this kind of code:

foreach (var item in items) {}

项目 T [] 的IEnumerable&LT; T&GT;

比,如果我需要的物品的数量,会在 Array.Count 结束快的IEnumerable&LT; T&GT; .Count之间()

Than, if I need to get the count of the items, would the Array.Count be faster over the IEnumerable<T>.Count()?

推荐答案

的IEnumerable&LT; T&GT; 一般是在这里一个更好的选择,因为在其他地方上市的原因。不过,我想提出关于一个点计数()。昆廷是不正确时,他说该类型自身实现计数()。它在 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之间并避免遍历整个序列。它仍然会比调用长度直接,因为计数()有发现,它实现了<$稍慢C $ C>的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.

这篇关于IEnumerable的&LT; T&GT; VS T []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆