Performance von Skip (und ähnlichen Funktionen wie Take)

Ich habe mir gerade den Quellcode der angesehenSkip/Take Erweiterungsmethoden von .NET Framework (auf derIEnumerable<T> Typ) und stellte fest, dass die interne Implementierung mit demGetEnumerator Methode:

// .NET framework
    public static IEnumerable<TSource> Skip<TSource>(this IEnumerable<TSource> source, int count)  
    {
        if (source == null) throw Error.ArgumentNull("source"); 
        return SkipIterator<TSource>(source, count); 
    }

    static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count) 
    {
        using (IEnumerator<TSource> e = source.GetEnumerator()) 
        {
            while (count > 0 && e.MoveNext()) count--;
            if (count <= 0) 
            { 
                while (e.MoveNext()) yield return e.Current;
            } 
        } 
    }

Angenommen, ich habe eineIEnumerable<T> mit 1000 Elementen (zugrunde liegender Typ istList<T>). Was passiert, wenn ich list.Skip (990) .Take (10) mache? Wird es durch die ersten 990 Elemente iterieren, bevor es die letzten zehn nimmt? (so verstehe ich es). Wenn ja, dann verstehe ich nicht, warum Microsoft das nicht implementiert hatSkip Methode wie folgt:

    // Not tested... just to show the idea
    public static IEnumerable<T> Skip<T>(this IEnumerable<T> source, int count)
    {
        if (source is IList<T>)
        {
            IList<T> list = (IList<T>)source;
            for (int i = count; i < list.Count; i++)
            {
                yield return list[i];
            }
        }
        else if (source is IList)
        {
            IList list = (IList)source;
            for (int i = count; i < list.Count; i++)
            {
                yield return (T)list[i];
            }
        }
        else
        {
            // .NET framework
            using (IEnumerator<T> e = source.GetEnumerator())
            {
                while (count > 0 && e.MoveNext()) count--;
                if (count <= 0)
                {
                    while (e.MoveNext()) yield return e.Current;
                }
            }
        }
    }

Tatsächlich taten sie das für dieCount Methode zum Beispiel ...

    // .NET Framework...
    public static int Count<TSource>(this IEnumerable<TSource> source) 
    {
        if (source == null) throw Error.ArgumentNull("source");

        ICollection<TSource> collectionoft = source as ICollection<TSource>; 
        if (collectionoft != null) return collectionoft.Count;

        ICollection collection = source as ICollection; 
        if (collection != null) return collection.Count; 

        int count = 0;
        using (IEnumerator<TSource> e = source.GetEnumerator())
        { 
            checked 
            {
                while (e.MoveNext()) count++;
            }
        } 
        return count;
    } 

Was ist der Grund?

Antworten auf die Frage(3)

Ihre Antwort auf die Frage