Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

c# - Is ToArray() optimized for arrays?

ReSharper suggested to enumerate an IEnumerable<T> to a list or array since I had "possible multiple enumerations of IEnumerable<T>".

The automatic code re-factoring suggested has some optimization built in to see whether IEnumerable<T> already is an array before calling ToArray().

var list = source as T[] ?? source.ToArray();
  • Isn't this optimization already built-in the original LINQ method?
  • If not, what would be the motivation not to do so?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Nope, there is no such optimization. If source is ICollection, then it will be copied to new array. Here is code of Buffer<T> struct, which used by Enumerable to create array:

internal Buffer(IEnumerable<TElement> source)
{    
    TElement[] array = null;
    int length = 0;
    ICollection<TElement> is2 = source as ICollection<TElement>;
    if (is2 != null)
    {
         length = is2.Count;
         if (length > 0)
         {
             array = new TElement[length]; // create new array
             is2.CopyTo(array, 0); // copy items
         }
    }
    else // we don't care, because array is ICollection<TElement>

    this.items = array;
}

And here is Enumerable.ToArray() method:

public static TSource[] ToArray<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    Buffer<TSource> buffer = new Buffer<TSource>(source);
    return buffer.ToArray(); // returns items
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...