22 lines
1.7 KiB
Plaintext
22 lines
1.7 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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.
|
|
|
|
It is important to enable this rule with caution, as performance outcomes can vary significantly across different runtimes. Notably, the https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-9/#collections[performance improvements in .NET 9] have brought `Any` closer to the performance of collection-specific `Exists` methods in most scenarios.
|
|
|
|
*Applies to*
|
|
|
|
* https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.exists[List]
|
|
* https://learn.microsoft.com/en-us/dotnet/api/system.array.exists[Array]
|
|
* https://learn.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutablelist-1.exists[ImmutableList]
|
|
|
|
=== 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 `https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/linq-to-entities[LINQ to Entities]` relies a lot on `System.Linq` for https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/linq-to-entities#query-conversion[query conversion], this rule won't raise when used within LINQ to Entities syntaxes.
|