1. 程式人生 > 程式設計 >詳解C# List<T>的Contains,Exists,Any,Where效能對比

詳解C# List<T>的Contains,Exists,Any,Where效能對比

測試

新建一個Person類

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

  }

初始化List 中有一百萬條資料,然後分別通過每種方法判斷xiaoming是否在List中,程式碼如下

static void Main(string[] args)
    {
      List<Person> persons = new List<Person>();
      //初始化persons資料
      for (int i = 0; i < 1000000; i++)
      {
        Person person = new Person("My" + i,i);
        persons.Add(person);
      }
      Person xiaoming=new Person("My999999",999999);
      
      //下面通過三種方法判斷persons中是否包含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耗時:" + watch.Elapsed.TotalMilliseconds);
      Console.WriteLine("Exists耗時:" + watch1.Elapsed.TotalMilliseconds);
      Console.WriteLine("Where耗時:" + watch2.Elapsed.TotalMilliseconds);
      Console.WriteLine("Any耗時:" + watch3.Elapsed.TotalMilliseconds);
      Console.ReadLine();
    }

執行結果如下圖所示

詳解C# List<T>的Contains,Exists,Any,Where效能對比

結論

通過上圖可以看出效能排序為

Contains > Exists > Where > Any

注意:
Contains中不能帶查詢條件

到此這篇關於詳解C# List<T>的Contains,Where效能對比的文章就介紹到這了,更多相關C# Contains,Where內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!