为什么不跳过()中的LINQ to对象优化? [英] Why isn't Skip() in LINQ to objects optimized?

查看:141
本文介绍了为什么不跳过()中的LINQ to对象优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于为什么不跳过()中的LINQ to对象优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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