I was reading through a question asking Is it better to call ToList() or ToArray() in LINQ queries? and found myself wondering why Enumerable.ToArray()
wouldn't first just call the Count()
method to find the size of the collection instead of using the internal Buffer{T}
class which dynamically resizes itself. Something like the following:
T[] ToArray<T>(IEnumerable<T> source)
{
var count = source.Count();
var array = new T[count];
int index = 0;
foreach (var item in source) array[index++] = item;
return array;
}
I know that we can't understand what is going through the minds of the designers and implementers and I'm sure they're much smarter than myself. So the best way to ask this question is what's wrong with the approach shown above? It seems to be less memory allocation and still operates in O(n) time.