Well I encounter many situations where having an IEnumerable is not enough. However I'm unsure about the performance of the above method calls.
What I really want to ask is:
Is the performance of ToList/ToArray:
If I called a linq extention method on a list, it has an O(1) performance if I call ToList but O(n) if call ToArray (and the opposite if my original list was an array) ?
Some magic happens and the performance is O(1)?
Probably to Dictionary is O(n), right ?
However, if the Count isn't known in advance, the only difference between ToArray() and ToList() is that the former has to trim the excess, which involves copying the entire array, whereas the latter doesn't trim the excess, but uses an average of 25% more memory.
The ToList method allows us to obtain a list of elements of a database using Entity Framework. We could say that it is the default method that people use to bring collections of records. This is due to the powerful amount of methods that lists offer us.
The ToList<TSource>(IEnumerable<TSource>) method forces immediate query evaluation and returns a List<T> that contains the query results. You can append this method to your query in order to obtain a cached copy of the query results.
Is the performance of
ToList
/ToArray
an O(n) operation which copies theIEnumerable
to a new array/List ?
Yes. ToList
is slightly more efficient, as it doesn't need to trim the internal buffer to the right length first.
If I called a linq extention method on a list, it has an O(1) performance if I call ToList but O(n) if call ToArray (and the opposite if my original list was an array) ?
No. For both calls, a new collection is always created; that's a shallow copy of the original collection. It's more efficient to call ToList
or ToArray
on any ICollection<T>
than on a simple IEnumerable<T>
which doesn't implement ICollection<T>
though, as with a collection the length is known to start with. (This is detected at execution time though; you don't need to worry about the compile-time type.)
Probably to Dictionary is O(n), right ?
Assuming the hash is sensible, it's O(N), yes. Basically it creates a new dictionary in exactly the way you'd probably expect it to.
You might want to read the corresponding posts in my Edulinq blog series:
ToList
ToArray
ToDictionary
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