Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't Skip() in LINQ to objects optimized?

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

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

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.

like image 981
codymanix Avatar asked Jun 05 '11 19:06

codymanix


1 Answers

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++];
    }

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.

like image 117
Gabe Avatar answered Oct 11 '22 08:10

Gabe