linq - What's more efficient in .Any and .Count in C# (Extension methods) -
this question has answer here:
public void methodname(observablecollection<datacollection> datacollection) { if (datacollection != null) { ischecked = datacollection.any(o => o.datacollectionid.equals(30)); ischecked = datacollection.where(o => o.datacollectionid.equals(30)).count() > 0; } }
can explain me, efficient way use above 2 filtering? .any? or .where.count?
note: consider datacollection has on 10,000 items.
please advice me. thank you
reviewing framework... depends. initial instincts in hypothetical-land:
any()
checks see if there single value. if so, returns true. o(1) operation.
count()
have either 1 of following:1) access running tally of items in collection, or 2) count items in collection
in best case (#1) operation o(1). in worst, (#2), it's o(n).
in reality, any()
uses collection's iterator determine if there next value. so, collection whether or not any()
o(1) operation. if poor implementation, possibly o(n).
for example, let's array iterator stupid, , looks first non-null value. has examine each item in array, , therefore any()
in case means o(n). (in fact, any()
returns true
array of length > 1).
count()
attempts see if collection implements icollection
or icollection<t>
, , if so, returns count
property's value. if underlying implementation keeps running tab, o(1). if not, o(n) worst case.
if enumerable doesn't implement 1 of interfaces, count()
iterates entire collection, counting on way. that's o(n).
tl;dr: according implementation, any()
more faster count()
.
Comments
Post a Comment