this post is to check performance to check if a collection or list contain any element:
public static IEnumerable
public static void A()
var b = new List
public static void B()
var b = l.Count();
My first impression is the new + .Count could be slower than, but actually it is very fast.
- A uses 7 ticks
- B uses 1921 ticks
But thing got to change after increase the size of this list from 10 to 1000000
- A uses 55858 ticks
- B uses 26076 ticks
Let us not use Count, we use Any.
- A uses 55012 ticks
- B uses 3142 ticks
The conclusion will be:
for a small size collection, convert it to a List
and check Count is faster. Otherwise, use Any() will be the best choice.