Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Linq optimizes execution based on real collection type?

Tags:

c#

.net

linq

Linq to objects works on any IEnumerable object. The variables

string[] foo = new string[] { };

and

var bar = new List<string>();

are both IEnumerable<string>, but if I want to know how many items each one of them has, I can use Length property on the array and Count property on the list. Or I can use the Count method from Linq, which will work for both.

The question is: does Linq provides some kind of optimization, such as implement different algorithms for every method, calling one or another depending on the actual type of the object being queried?

I imagine something like this:

if (obj is Array<T>)
    DoSomethingForArray(obj as Array<T>);
else if (obj is List<T>)
    DoSomethingForList(obj as List<T>);
else if (obj is Collection<T>)
    DoSomethingForCollection(obj as Collection<T>);
else
   DoSomethingThatWorksForAnyIEnumerable(obj);
like image 839
Doug Avatar asked Dec 18 '12 20:12

Doug


1 Answers

The answer is: it depends - The Linq extension method Count() checks if the type implements ICollection<T> or ICollection and uses the Count property of that if possible, but it doesn't optimize for every possible scenario.

like image 176
Brian Rasmussen Avatar answered Nov 03 '22 01:11

Brian Rasmussen