If I have the following IEnumerable list which comes from some repository.
IEnumerable<SomeObject> items = _someRepo.GetAll();
What is faster:
items.Count(); // Using Linq on the IEnumerable interface.
or
List<SomeObject> temp = items.ToList<SomeObject>(); // Cast as a List
temp.Count(); // Do a count on a list
Is the Linq Count() faster or slower than casting the IEnumerable to a List and then performing a Count()?
Update: Improved the question a little bit to a bit more realistic scenario.
Calling
Countdirectly is a better choice.Enumerable.Counthas some performance improvements built in that will let it return without enumerating the entire collection:ToList()uses similar optimizations, baked intoList<T>(IEnumerable<T> source)constructor:But as you can see it only uses generic
ICollection<T>, so if your collection implementsICollectionbut not its generic version callingCount()directly will be much faster.Not calling
ToListfirst also saves you an allocation of newList<T>instance - not something overly expensive, but it's always better to avoid unnecessary allocation when possible.