You can read all the C# performance tips from the following links,
- C# Programming Performance Tips - Part One - String Split
- C# Programming Performance Tips - Part Two - String Equals
- C# Programming Performance Tips - Part Three - Adding Strings
- C# Programming Performance Tips - Part Four - List.Count() Vs List.Any()
- C# Programming Performance Tips - Part Five - List.Count() Vs List.Count
- 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);
The result suggests that we should use List.Any() over List.Count() wherever possible.