菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
102
0

详解C# List<T>的Contains,Exists,Any,Where性能对比

原创
05/13 14:22
阅读数 501043

新建一个Person类

public class Person
  {
    public Person(striwww.cppcns.comng 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 (inthttp://www.cppcns.com i = 0; i < 10ptDtmoHuD00000; 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.S编程客栈top();

      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耗时:ptDtmoHuD" + 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,Exists,Any,Where性能对比的文章就介绍到这了,更多相关C# Contains,Exists,Any,Where内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

本文标题: 详解C# List<T>的Contains,Exists,Any,Where性能对比
本文地址: http://www.cppcns.com/ruanjian/csharp/369134.html

发表评论

0/200
102 点赞
0 评论
收藏
为你推荐 换一批