栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解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 persons = new List();
      //初始化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();
    }

执行结果如下图所示

结论

通过上图可以看出性能排序为

Contains > Exists > Where > Any

注意:
Contains中不能带查询条件

到此这篇关于详解C# List<T>的Contains,Exists,Any,Where性能对比的文章就介绍到这了,更多相关C# Contains,Exists,Any,Where内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/121590.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号