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

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

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

  1. C# Programming Performance Tips - Part One - String Split
  2. C# Programming Performance Tips - Part Two - String Equals
  3. C# Programming Performance Tips - Part Three - Adding Strings
  4. C# Programming Performance Tips - Part Four - List.Count() Vs List.Any()
  5. C# Programming Performance Tips - Part Five - List.Count() Vs List.Count
  6. C# Programming Performance Tips - Part Six - Array Length

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()

Stopwatch watch = new Stopwatch();  
List < string > strs = new List < string > () {  
    "Akshay",  
    "Patel",  
    "Panth",  
    "Patel"  
};  
watch.Start();  
if (strs.Count() > 0) {}  
Console.WriteLine("List.Count()-{0}", watch.Elapsed);

List.Any()

watch.Restart();  
if (strs.Any()) {}  
Console.WriteLine("List.Any() - {0}", watch.Elapsed);

C# Programming Performance Tips - Part Four - img1.png

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