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?
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.