I just take a look at our code base’s history and found a check-in that change from this:
public virtual T[] ToArray()
{
List<T> list = new List<T>();
foreach (object item in List)
{
list.Add((T)item);
}
return list.ToArray();
}
to this:
public virtual T[] ToArray()
{
T[] result = new T[List.Count];
for (int i = 0; i < List.Count; ++i)
{
result[i] = (T)List[i];
}
return result;
}
with the comment: Optimized ToArray implementation to avoid creating multiple data structures in the process.
I wonder myself why there’s an optimization here. for() may be faster than foreach(), but where’s the “creating multiple data structures”?
P/S: The guy who wrote this is on vacation now
In the original code, you create a
List<T>– without specifying a capacity, so it could involve copying the internal array several times – and then you callToArrayon theList<T>, resulting in a copy.The newer version doesn’t do that. It creates one array, and copies the original list into it.
Admittedly just using LINQ’s
ToArraymethod would be simpler and quite possibly even more efficient, and it’s not clear why this is a virtual method to start with, but…