Convert IEnumerable To List

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

Which is more efficient:

  • myEnumerable.ToList()

  • or new List<T>(myEnumerable)

Thanks!

+6
source share
3 answers

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

myEnumerable.ToList() will do a new List<T>(myEnumerable) under the hood, but first checks to see if the collection is null and throws an exception, if any. If you know that myEnumerable is not null, you can use ToList ().

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

+6
source

The first challenge is the second, so they will be identical for all purposes.

JITter can embed the ToList() method, which will make them identical modulo zero check. And perhaps the null check in Enumerable<T>.ToList() redundant, since the List<T> constructor that it calls also performs a null check.

+4
source

It would be the same. (The first is more readable.)

+2
source

Source: https://habr.com/ru/post/946002/


All Articles