I just want know if a “FindAll” will be faster than a “Where” extentionMethod and why?
Example :
myList.FindAll(item=> item.category == 5);
or
myList.Where(item=> item.category == 5);
Which is better ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Well,
FindAllcopies the matching elements to a new list, whereasWherejust returns a lazily evaluated sequence – no copying is required.I’d therefore expect
Whereto be slightly faster thanFindAlleven when the resulting sequence is fully evaluated – and of course the lazy evaluation strategy ofWheremeans that if you only look at (say) the first match, it won’t need to check the remainder of the list. (As Matthew points out, there’s work in maintaining the state machine forWhere. However, this will only have a fixed memory cost – whereas constructing a new list may require multiple array allocations etc.)Basically,
FindAll(predicate)is closer toWhere(predicate).ToList()than to justWhere(predicate).Just to react a bit more to Matthew’s answer, I don’t think he’s tested it quite thoroughly enough. His predicate happens to pick half the items. Here’s a short but complete program which tests the same list but with three different predicates – one picks no items, one picks all the items, and one picks half of them. In each case I run the test fifty times to get longer timing.
I’m using
Count()to make sure that theWhereresult is fully evaluated. The results show that collecting around half the results, the two are neck and neck. Collecting no results,FindAllwins. Collecting all the results,Wherewins. I find this intriguing: all of the solutions become slower as more and more matches are found:FindAllhas more copying to do, andWherehas to return the matched values instead of just looping within theMoveNext()implementation. However,FindAllgets slower faster thanWheredoes, so loses its early lead. Very interesting.Results:
(Compiled with /o+ /debug- and run from the command line, .NET 3.5.)
Code: