When it comes to performance in C#, even small inefficiencies can add up in large codebases. One common example is the use of the LINQ method .Any()
on arrays and lists instead of directly checking .Length
or .Count
. While .Any()
improves readability in some contexts, it introduces measurable overhead when used with collections that already expose a count property.
Using BenchmarkDotNet, I compared .Any()
with .Length > 0
for a 100-element integer array. The difference was significant.
Method | Mean | Error | StdDev | Allocated |
---|---|---|---|---|
Any | 5.5362 ns | 1.0495 ns | 0.0575 ns | - |
Length | 0.2413 ns | 0.1316 ns | 0.0072 ns | - |
As shown above, checking .Length
is roughly 30 times faster than using .Any()
on an array. The reason is simple: .Length
is a direct property access, while .Any()
adds the overhead of an enumerator.
The same comparison was performed using a List<int>
. The results are even more striking.
Method | Mean | Error | StdDev | Allocated |
---|---|---|---|---|
Any | 2.3934 ns | 0.0325 ns | 0.0018 ns | - |
Count | 0.0000 ns | 0.0000 ns | 0.0000 ns | - |
For lists, .Count
is effectively instantaneous in this benchmark context - it’s a property access resolved at compile time. In contrast, .Any()
must still perform a method call and a single enumerator step.
.Any()
Is Slower
The LINQ implementation of .Any()
does have some optimization routes (if the source list implements ICollection
it's smart enough to detect that, but the overhead is still there. And for everything else it simply obtains an enumerator and calls .MoveNext()
once to check for the presence of elements. This abstraction introduces a small but measurable overhead compared to directly checking .Count
or .Length
.
When working with IEnumerable<T>
- especially when the underlying type is not known - .Any()
remains the correct and idiomatic choice. However, for arrays and lists where you can access .Count
or .Length
, prefer those properties for both clarity and performance.
In fact, Visual Studio’s code analysis tools will suggest this optimization automatically, recommending direct property checks instead of .Any()
when the collection type allows it.