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

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

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

In this blog, we will do benchmarking for List.Count() which is a method and List.Count which is a property.

List<string> strs = new List<string>() { "Akshay", "Patel", "Panth", "Patel" };  
Stopwatch watch = new Stopwatch();

List.Count()

watch.Start();  
int count = strs.Count();  
Console.WriteLine("Count()-{0}", watch.Elapsed);

List.Count

watch.Restart();  
int count1 = strs.Count;  
Console.WriteLine("Count - {0}", watch.Elapsed);

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

Thus, as we can see, whenever we want to get the count of a list, we should use the List.Count property.