欢迎光临
我的个人博客网站

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中不能带查询条件

赞(0) 打赏
未经允许不得转载:张拓的天空 » C# List<T>的Contains, Exists, Any,Where性能对比
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

专业的IT技术经验分享 更专业 更方便

联系我们本站主机

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏