If i want to convert Enumerable (IEnumerable<T>
) to list.
What is more efficient:
myEnumerable.ToList()
or new List<T>(myEnumerable)
Thanks!
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.
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.
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