Explain the performance comparison of contains, exists, any and where in C# list in detail

Test
create a new person class

public class Person
  {
    public Person(string name,int id)
    {
      Name = name;
      Id = id;
    }
    public string Name { get; set; }
    public int Id { get; set; }
 
  }

Initialize a million pieces of data in the list, and then use each method to determine whether Xiaoming is in the list. The code is as follows

static void Main(string[] args)
    {
      List<Person> persons = new List<Person>();
      //Initialize persons data
      for (int i = 0; i < 1000000; i++)
      {
        Person person = new Person("My" + i,i);
        persons.Add(person);
      }
      Person xiaoming=new Person("My999999", 999999);
       
      //The following three methods are used to determine whether persons contain xiaoming
      Stopwatch watch = new Stopwatch();
      watch.Start();
      bool a = persons.Contains(xiaoming);
      watch.Stop();
 
      Stopwatch watch1 = new Stopwatch();
      watch1.Start();
      bool b = persons.Exists(x=>x.Id==xiaoming.Id);
      watch1.Stop();
 
      Stopwatch watch2 = new Stopwatch();
      watch2.Start();
      bool c = persons.Where(x=>x.Id==xiaoming.Id).Any();
      watch2.Stop();
 
      Stopwatch watch3 = new Stopwatch();
      watch3.Start();
      bool d = persons.Any(x => x.Id == xiaoming.Id);
      watch3.Stop();
 
      Console.WriteLine("Contains time:" + watch.Elapsed.TotalMilliseconds);
      Console.WriteLine("Exists time:" + watch1.Elapsed.TotalMilliseconds);
      Console.WriteLine("Where time:" + watch2.Elapsed.TotalMilliseconds);
      Console.WriteLine("Any time:" + watch3.Elapsed.TotalMilliseconds);
      Console.ReadLine();
    }

The execution result is shown in the figure below

Conclusion
it can be seen from the figure above that the performance ranking is

Contains > Exists > Where > Any

Note:
no query conditions are allowed in contains

This article about the detailed explanation of C # list contains, exists, any, where performance comparison is introduced here. For more related C # contains, exists, any, where content, please search the previous articles of C # tutorial script home or continue to browse the following related articles. I hope you can support more in the future


Read More: