Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance Difference between using ToList() vs. new List(IEnumerable<T>)

Tags:

c#

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 image 457
Loren Shaw Avatar asked Apr 11 '14 17:04

Loren Shaw


Video Answer


1 Answers

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.

like image 119
svick Avatar answered Oct 19 '22 07:10

svick