Introduction
In this modern era of enterprises application, entity framework playing a key role in dealing with the databases. so we need to follow the best practices in each statements of our code to speedup. Sometimes we developers will have multiple options to check the same condition. We must choose the best option else it will cost to us. Let's have this scenario, we need to check whether our collection object is having any elements in LINQ. We can use Any() method or Count()>0, still this is debatable topic in many technical forums. So, I decided to create this article for the developers who is having same thought which I am having. Let's conclude is our way
Approaches
Performance checking for Any and Count LINQ Methods is trickiest thing over ICollection<T> and IEnumerable<T>
- ICollection<T> Count is better performer than Any Method
- IEnumerable<T> Any is best option, no availability of Count property
Public API
To check the performance, I need some amount of data which should already available. So I decided to choose this public api. Thanks to publicapis
Public API Models
Entry class
using System;
using System.Collections.Generic;
using System.Text;
namespace AnyVsCount
{
public class Entry
{
public string API { get; set; }
public string Description { get; set; }
public string Auth { get; set; }
public bool HTTPS { get; set; }
public string Cors { get; set; }
public string Link { get; set; }
public string Category { get; set; }
}
}
using System; using System.Collections.Generic; using System.Text; namespace AnyVsCount { public class Entry { public string API { get; set; } public string Description { get; set; } public string Auth { get; set; } public bool HTTPS { get; set; } public string Cors { get; set; } public string Link { get; set; } public string Category { get; set; } } }
Root Collection
using System; using System.Collections.Generic; using System.Text; namespace AnyVsCount { public class RootCollection { public int count { get; set; } public ICollection<Entry> entries { get; set; } } }
ICollection<T> Count is better performer than Any Method
Tick Count Based Approach ICollection<T>
For Any() and Count()>0 method comparisons we will evaluate based on tick counts in executing the LINQ Statement.
using Newtonsoft.Json; using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace AnyVsCount { class Program { static async Task Main(string[] args) { Console.WriteLine("Who is better performer Any or Count>0 (ICollection<T>)?"); var client = new HttpClient(); var response = await client.GetAsync("https://api.publicapis.org/entries"); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); var coll = JsonConvert.DeserializeObject<RootCollection>(data); Console.WriteLine("Evaluating Any Method:"); Console.WriteLine("-----------------------"); var watch3 = System.Diagnostics.Stopwatch.StartNew(); // the code that you want to measure comes here var result3 = coll.entries.Any(); watch3.Stop(); var elapsedMs3 = watch3.ElapsedTicks; Console.WriteLine("ICollection<T>.Any : " + elapsedMs3 + " Ticks"); Console.WriteLine("-----------------------"); Console.WriteLine(" "); Console.WriteLine("Evaluating Count>0 Method:"); Console.WriteLine("-----------------------"); var watch7 = System.Diagnostics.Stopwatch.StartNew(); // the code that you want to measure comes here var result7 = coll.entries.Count > 0; watch7.Stop(); var elapsedMs7 = watch7.ElapsedTicks; Console.WriteLine("ICollection<T>.Count > 0 : " + elapsedMs7 + " Ticks"); Console.WriteLine("-----------------------"); Console.ReadKey(); } } } }
Debug Video ICollection<T>
ICollection<T> Performance Result
After multiple attempts in my local machine , For ICollection<T> Count > 0 is performing better than Any
Why Count is better performer than Any for ICollection<T>?
According to the source .NET Core source, ICollection<T> just calls the Count method for optimization, but Any method needs to be enumerated. That's why Any is slower than Count.IEnumerable<T> Any is best option, no availability of Count property
For IEnumerable<T> types , we know that Count property is not available and execution of Any method is very fast as it enumerate over single item to identify the result. It will not loop over items to get count or length.
Root Enumerable
using System; using System.Collections.Generic; using System.Text; namespace AnyVsCount { public class RootEnumerable { public int count { get; set; } public IEnumerable<Entry> entries { get; set; } } }
Tick Count Based Approach IEnumerable<T>
using Newtonsoft.Json; using System; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace AnyVsCount { class Program { static async Task Main(string[] args) { Console.WriteLine("Who is better performer Any or Count>0 (IEnumerable<T>)?"); var client = new HttpClient(); var response = await client.GetAsync("https://api.publicapis.org/entries"); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); var coll = JsonConvert.DeserializeObject<RootEnumerable>(data); Console.WriteLine("Evaluating Any Method:"); Console.WriteLine("-----------------------"); var watch3 = System.Diagnostics.Stopwatch.StartNew(); // the code that you want to measure comes here var result3 = coll.entries.Any(); watch3.Stop(); var elapsedMs3 = watch3.ElapsedTicks; Console.WriteLine("IEnumerable<T>.Any : " + elapsedMs3 + " Ticks"); Console.WriteLine("-----------------------"); Console.WriteLine(" "); Console.WriteLine("-----------------------"); Console.ReadKey(); } } } }
IEnumerable<T> Performance Results
IEnumerable can use Count() method for optimization but Any() will look for element and stop its iteration
Any Method will always be good for readability and good performer over IEnumerable types while Count > 0 is better performer for ICollection types. But both methods has its pros and cons. Hope you like this article
Comments
Post a Comment