C# Programming Performance Tips - Part Four - List.Count() Vs List.Any()

You can read all the C# performance tips from the following links,

Many times, developers use List.Count() to check whether a list has data or is empty, before iterating. Here, we will compare the execution time of List.Count() and List.Any(). 

List.Count()
  1. Stopwatch watch = new Stopwatch();  
  2. List < string > strs = new List < string > () {  
  3.     "Akshay",  
  4.     "Patel",  
  5.     "Panth",  
  6.     "Patel"  
  7. };  
  8. watch.Start();  
  9. if (strs.Count() > 0) {}  
  10. Console.WriteLine("List.Count()-{0}", watch.Elapsed);  
List.Any()
  1. watch.Restart();  
  2. if (strs.Any()) {}  
  3. Console.WriteLine("List.Any() - {0}", watch.Elapsed);  
Result
 
List.Count() Vs List.Any()

The result suggests that we should use List.Any() over List.Count() wherever possible.