Linq Any() performance compared to Count() > 0
I often see
.Count() > 0 or
.Count > 0 to check if there are any elements in some collection. Linq provides an
Any() method to check if there are any elements.
Any() sure reads better but does it come with any downsides? Inspired by a twitter post on using
Any() and benchmarking it, I decided to run some of my own tests using BenchmarkDotNet.
The benchmarks that were run compare the use of these two methods, comparing enumerables and lists with two sizes, 1000 and 1000.
BenchmarkDotNet=v0.13.0, OS=Windows 10.0.19042.985 (20H2/October2020Update) Intel Core i7-8650U CPU 1.90GHz (Kaby Lake R), 1 CPU, 8 logical and 4 physical cores