Convert IEnumerable To List

10,224

Solution 1

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.

Solution 2

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.

Solution 3

Would be the same. (First is more readable.)

Share:
10,224

Related videos on Youtube

user436862
Author by

user436862

Updated on June 04, 2022

Comments

  • user436862
    user436862 almost 2 years

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

    What is more efficient:

    1. myEnumerable.ToList()

    2. or new List<T>(myEnumerable)

    Thanks!

    • Nahum
      Nahum almost 11 years
      I am too lazy to use refletor but probably myEnumerable.ToList() calls new List<T>(myEnumerable)