Possible Duplicate:
Is it better to call ToList() or ToArray() in LINQ queries?
I have code like this:
void Foobar(string[] arr, Dictionary<string, string[]>)
{
var t = arr.Intersect(dic.Keys).ToList(); // .or ToArray() ?
foreach(var item in t)
{
..
}
var j = t.Count; // also I need this
}
which method is preferred?
I could go without any but I need to know the size and I don't want to call Enumerable.Count<T>()
- it seems do do more actions then Array<T>.Size
or List<T>.Count
. Am I right?
It's much more common to see a lot of ToArray calls which are immediately passed to other short lived uses of memory in which case ToList is demonstrably better.
ToList() does have a performance impact, it is an O(n) operation though it will likely only require attention in performance critical operations.
Across the array sizes the Any is roughly 1/3 faster than using Count .
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.
Actually, in the current MS implementation of Count(IEnumerable) there's a shortcut looking if the IEnumerable is an ICollection and calls Count on it. So the performance should be comparable for counting elements.
ToList and ToArray are a bit the same. If the IEnumerable is a ICollection, then the CopyTo method is called instead, which is a bit faster.
So, choose what makes your code the most readable, and benchmark for YOUR use case to have a definite answer.
Update: I did a naive benchmark.
Starting with an Array: var items = Enumerable.Range(1,1000).ToArray();
Starting with an IEnumerable: var items = Enumerable.Range(1,1000);
So basically you get comparable performance.
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