I was curious as to the performance impact of using ToList() on an IEnumerable versus just calling the List Constructor 'List(IEnumerable)'.
Example:
int[] testArray = new int[10];
var list = testArray.ToList();
vs.
int[] testArray = new int[10];
var list = new List<int>(testArray);
Is there any performance impact or best practice in using one over the other?
I've taken over an application where the controller methods I'm calling returns an array, but the views I have are expecting a List.
Like others already said, most of the time the best practice is to do what is more readable (which I think here means using ToList()
). Both ways do exactly the same thing, so you should expect that their performance to be very similar.
If profiling shows that this is the code you need to optimize, then you should try it both ways and measure which one is faster.
And looking at the source code (in the case of .Net base libraries, you can look at Reference Source or use a decompiler) might help too. ToList
looks like this:
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
return new List<TSource>(source);
}
So, its performance should be the same as new List
, plus one null
check and one method call. But both of the additions are likely to be optimized away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With