Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 920
Steven Jeuris Avatar asked Dec 09 '12 18:12

Steven Jeuris


People also ask

What is faster ToList or ToArray?

ToArray might do an additional allocation and copy operation such that the buffer will be sized exactly to the number of elements. In order to confirm this the following benchmark is used. The results confirm that ToList is in most cases 10% - 15% faster.

Does ToArray create a copy Java?

The ToArray method is used to create an array and copy the stack elements to it, then the array is passed to the Stack<T> constructor that takes IEnumerable<T>, creating a copy of the stack with the order of the elements reversed.

Why use ToList in linq?

In LINQ, the ToList operator takes the element from the given source, and it returns a new List. So, in this case, input would be converted to type List.


1 Answers

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
}
like image 150
Sergey Berezovskiy Avatar answered Oct 13 '22 00:10

Sergey Berezovskiy