C# list < t > contains, exists, any, where performance comparison

Time:2021-9-23

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 listThere are one million pieces of data in the list, and then judge whether Xiaoming is in the list through each method. The code is as follows

static void Main(string[] args)
        {
            List persons = new List();
            //Initialize people data
            for (int i = 0; i < 1000000; i++)
            {
                Person person = new Person("My" + i,i);
                persons.Add(person);
            }
            Person xiaoming=new Person("My999999", 999999);
            
            //Here are three ways to determine whether Xiaoming is included in people
            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 results are shown in the figure below在这里插入图片描述

conclusion

As can be seen from the figure above, the performance order is
Contains > Exists > Where > Any

be careful:
The result of contains above is false, because even if the objects in Xiaoming and list are equal, their stored addresses are different. Thanks @ dumpling for the reminder

Recommended Today

Supervisor

Supervisor [note] Supervisor – H view supervisor command help Supervisorctl – H view supervisorctl command help Supervisorctl help view the action command of supervisorctl Supervisorctl help any action to view the use of this action 1. Introduction Supervisor is a process control system. Generally speaking, it can monitor your process. If the process exits abnormally, […]