Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IEnumerable To List

If i want to convert Enumerable (IEnumerable<T>) to list.

What is more efficient:

  1. myEnumerable.ToList()

  2. or new List<T>(myEnumerable)

Thanks!

like image 357
user436862 Avatar asked May 28 '13 11:05

user436862


2 Answers

They take more or less the same time to execute but new List<T>(myEnumerable) is a bit faster.

myEnumerable.ToList() will do a new List<T>(myEnumerable) under the hood, but it will first check if the collection is null and throw an exception if it is. If you know that myEnumerable is not null then you could use the ToList().

But, in my opinion, write the code that is easiest to read. This is a micro optimization that you should not spend too much time on.

like image 167
user707727 Avatar answered Oct 08 '22 09:10

user707727


The first calls the second, so they will be to all intents and purposes identical.

The JITter may well inline the ToList() method which will make them identical modulo a null check. And arguably the null check in Enumerable<T>.ToList() is redundant, since the List<T> constructor it calls also performs a null check.

like image 21
Joe Avatar answered Oct 08 '22 09:10

Joe