Both the List.Exists
method and IEnumerable.Any
method can be used to find the first element that satisfies a predicate
in a collection. However, List.Exists
can be faster than IEnumerable.Any
for List
objects, as well as requires
significantly less memory. For small collections, the performance difference may be negligible, but for large collections, it can be noticeable. The
same applies to ImmutableList
and arrays too.
Applies to
What is the potential impact?
We measured at least 3x improvement in execution time. For more details see the Benchmarks
section from the More info
tab.
Also, no memory allocations were needed for the Exists
method, since the search is done in-place.
Exceptions
Since LINQ to
Entities
relies a lot on System.Linq
for query conversion,
this rule won’t raise when used within LINQ to Entities syntaxes.