简体   繁体   English

Linq ToList / ToArray / ToDictionary表现

[英]Linq ToList/ToArray/ToDictionary performance

Well I encounter many situations where having an IEnumerable is not enough. 好吧,我遇到很多情况,IEnumerable是不够的。 However I'm unsure about the performance of the above method calls. 但是我不确定上述方法调用的性能。

What I really want to ask is: 我真正想问的是:

Is the performance of ToList/ToArray: 是ToList / ToArray的性能:

  1. an O(n) operation which copies the IEnumerable to a new array/List ? 一个O(n)操作,它将IEnumerable复制到一个新的数组/列表?
  2. If I called a linq extention method on a list, it has an O(1) performance if I call ToList but O(n) if call ToArray (and the opposite if my original list was an array) ? 如果我在列表上调用linq扩展方法,如果我调用ToList则它具有O(1)性能,如果调用ToArray则具有O(n)(如果我的原始列表是数组则相反)?

  3. Some magic happens and the performance is O(1)? 一些魔法发生了,性能是O(1)?

Probably to Dictionary is O(n), right ? 字典可能是O(n),对吧?

Is the performance of ToList / ToArray an O(n) operation which copies the IEnumerable to a new array/List ? ToList / ToArray的性能是否是将IEnumerable复制到新数组/列表的O(n)操作?

Yes. 是。 ToList is slightly more efficient, as it doesn't need to trim the internal buffer to the right length first. ToList稍微高效一些,因为它不需要先将内部缓冲区修剪到合适的长度。

If I called a linq extention method on a list, it has an O(1) performance if I call ToList but O(n) if call ToArray (and the opposite if my original list was an array) ? 如果我在列表上调用linq扩展方法,如果我调用ToList则它具有O(1)性能,如果调用ToArray则具有O(n)(如果我的原始列表是数组则相反)?

No. For both calls, a new collection is always created; 不会。对于这两个电话,总会创建一个新的集合; that's a shallow copy of the original collection. 这是原始集合的浅层副本。 It's more efficient to call ToList or ToArray on any ICollection<T> than on a simple IEnumerable<T> which doesn't implement ICollection<T> though, as with a collection the length is known to start with. 在任何ICollection<T>上调用ToListToArray比在没有实现ICollection<T>的简单IEnumerable<T>上调用更有效,就像已知长度的集合一样。 (This is detected at execution time though; you don't need to worry about the compile-time type.) (这在执行时检测到;您不必担心编译时类型。)

Probably to Dictionary is O(n), right ? 字典可能是O(n),对吧?

Assuming the hash is sensible, it's O(N), yes. 假设散列是合理的,那就是O(N),是的。 Basically it creates a new dictionary in exactly the way you'd probably expect it to. 基本上它会以您可能期望的方式创建一个新的字典。

You might want to read the corresponding posts in my Edulinq blog series: 您可能想阅读我的Edulinq博客系列中的相应帖子:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM