Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialcodey code
168 PointsShouldn't the methods Any() and All() have the same efficiency?
Suppose if in our Birds List, we have 5th element as Sparrow, then birds.Any(b => b.Name == "sparrow") returns true for 5th element and stops further evaluation
In the second case, birds.All(b => b.Name != "sparrow") returns false for the 5th element and stops further evaluation.
So, according to this, both of them have the same efficiency. Am I missing something?
2 Answers
Steven Parker
231,268 PointsThe efficiency is different if you use the same condition.
Since you're using different conditions, you've effectively made them equivalent in efficiency. But for the same condition, Any can return a true as soon as it finds a single item, but All cannot return true until it has examined every item.
Luis Marsano
21,425 PointsAm I missing something?
No, and what you've observed is De Morgan's Law: for any predicate p
,
enumerable.All(x => !p(x))
is logically equivalent to !enumerable.Any(p)
.
Both expressions short-circuit for precisely the same enumerable
and predicate p
(ie, as soon as p(x)
is true).
You make a good point: for a given predicate p
, you don't have much choice between quantifiers: you must choose between logically equivalent formulations, which also short-circuit identically.
Any situation where enumerable.Any(p)
is right, enumerable.All(p)
is likely wrong.
The presentation was a bit misleading in that respect.
However, if you have a choice among predicates, then any predicate that short-circuits a quantifier expression will also short-circuit the other logically equivalent quantifier expression.
So, just choose good predicates.