为什么不跳过()中的LINQ to对象优化?跳过、对象、LINQ、to

2023-09-03 02:45:49 作者:故里说长安

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

这将是巨大的,如果该查询将只使用,而不是遍历999999条目索引。

It would be great if this query would just use the indexer instead of traversing 999999 entries.

我看看到System.Core.dll的,发现相对于跳过()计数()扩展方法进行了优化。如果的IEnumerable 工具的ICollection 则只是调用了计数属性。

I had a look into the System.Core.dll and noticed that in contrast to Skip(), the Count() extension method is optimized. If the IEnumerable implements ICollection then it just calls the Count property.

推荐答案

如果你的我以一个类似的问题的答案,它看起来好像它应该很容易,以提供非幼稚的(即抛出适当的例外)跳过优化任何的IList

If you look at my answer to a similar question, it appears as though it should be easy to provide a non-naive (i.e. throws proper exceptions) optimization of Skip for any IList:

    public static IEnumerable<T> Skip<T>(this IList<T> source, int count)
    {
        using (var e = source.GetEnumerator())
            while (count < source.Count && e.MoveNext())
                yield return source[count++];
    }

当然,您的示例使用数组。因为数组迭代过程中没有抛出异常,甚至做任何事情可以复杂到我的功能是不必要的。因此,人们可以得出这样的结论MS没有优化,因为他们没想到它,或者他们不认为这是一个普通不过的情况下,不值得进行优化。

Of course, your example uses an array. Since arrays don't throw exceptions during iteration, even doing anything as complicated as my function would be unnecessary. One could thus conclude that MS didn't optimize it because they didn't think of it or they didn't think it was a common enough case to be worth optimizing.