Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to iterate and count. What is fastest or preferred: ToArray() or ToList()? [duplicate]

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?

like image 486
abatishchev Avatar asked Dec 01 '09 14:12

abatishchev


People also ask

Which is faster ToList or ToArray?

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.

Does ToList decrease performance?

ToList() does have a performance impact, it is an O(n) operation though it will likely only require attention in performance critical operations.

Is any faster than count?

Across the array sizes the Any is roughly 1/3 faster than using Count .

Why do we use ToList ()?

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.


1 Answers

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();

  • calling ToList() : 25ms / 10000
  • calling ToArray() : 23 ms / 10000

Starting with an IEnumerable: var items = Enumerable.Range(1,1000);

  • calling ToList() : 168ms / 10000
  • calling ToArray() : 171 ms / 10000

So basically you get comparable performance.

like image 193
Yann Schwartz Avatar answered Nov 13 '22 04:11

Yann Schwartz