gpt4 book ai didi

.net - 为什么 LINQ to objects 中的 Skip() 没有优化?

转载 作者:行者123 更新时间:2023-12-03 15:59:50 26 4
gpt4 key购买 nike

var res = new int[1000000].Skip(999999).First();

如果此查询仅使用索引器而不是遍历 999999 个条目,那就太好了。

我查看了 System.Core.dll 并注意到与 Skip() 形成对比的情况。 , Count()优化扩展方法。如果 IEnumerable工具 ICollection然后它只是调用 Count属性(property)。

最佳答案

我会让乔恩斯基特回答这个:

If our sequence is a list, we can just skip straight to the right part of it and yield the items one at a time. That sounds great, but what if the list changes (or is even truncated!) while we're iterating over it? An implementation working with the simple iterator would usually throw an exception, as the change would invalidate the iterator. This is definitely a behavioural change. When I first wrote about Skip, I included this as a "possible" optimization - and actually turned it on in the Edulinq source code. I now believe it to be a mistake, and have removed it completely.

...

The problem with both of these "optimizations" is arguably that they're applying list-based optimizations within an iterator block used for deferred execution. Optimizing for lists either upfront at the point of the initial method call or within an immediate execution operator (Count, ToList etc) is fine, because we assume the sequence won't change during the course of the method's execution. We can't make that assumption with an iterator block, because the flow of the code is very different: our code is visited repeatedly based on the caller's use of MoveNext().

https://msmvps.com/blogs/jon_skeet/archive/2011/01/26/reimplementing-linq-to-objects-part-40-optimization.aspx

关于.net - 为什么 LINQ to objects 中的 Skip() 没有优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6245172/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com