c# - Linq count vs IList count -
if have following ienumerable list comes repository.
ienumerable<someobject> items = _somerepo.getall(); what faster:
items.count(); // using linq on ienumerable interface. or
list<someobject> temp = items.tolist<someobject>(); // cast list temp.count(); // count on list is linq count() faster or slower casting ienumerable list , performing count()?
update: improved question little bit bit more realistic scenario.
calling count directly better choice.
enumerable.count has performance improvements built in let return without enumerating entire collection:
public static int count<tsource>(this ienumerable<tsource> source) { if (source == null) throw error.argumentnull("source"); icollection<tsource> collectionoft = source icollection<tsource>; if (collectionoft != null) return collectionoft.count; icollection collection = source icollection; if (collection != null) return collection.count; int count = 0; using (ienumerator<tsource> e = source.getenumerator()) { checked { while (e.movenext()) count++; } } return count; } tolist() uses similar optimizations, baked list<t>(ienumerable<t> source) constructor:
public list(ienumerable<t> collection) { if (collection==null) throwhelper.throwargumentnullexception(exceptionargument.collection); contract.endcontractblock(); icollection<t> c = collection icollection<t>; if( c != null) { int count = c.count; if (count == 0) { _items = _emptyarray; } else { _items = new t[count]; c.copyto(_items, 0); _size = count; } } else { _size = 0; _items = _emptyarray; // enumerable empty. let add allocate new array, if needed. // note go _defaultcapacity first, not 1, 2, etc. using(ienumerator<t> en = collection.getenumerator()) { while(en.movenext()) { add(en.current); } } } } but can see uses generic icollection<t>, if collection implements icollection not generic version calling count() directly faster.
not calling tolist first saves allocation of new list<t> instance - not overly expensive, it's better avoid unnecessary allocation when possible.
Comments
Post a Comment