这篇文章主要介绍了详解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
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();
}
执行结果如下图所示
结论
通过上图可以看出性能排序为
Contains > Exists > Where > Any
注意:
Contains中不能带查询条件
到此这篇关于详解C# List<T>的Contains,Exists,Any,Where性能对比的文章就介绍到这了,更多相关C# Contains,Exists,Any,Where内容请搜索得得之家以前的文章希望大家以后多多支持得得之家!
沃梦达教程
本文标题为:详解C# List<T>的Contains,Exists,Any,Where性能对比
猜你喜欢
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- C++ 数据结构超详细讲解顺序表 2023-03-25
- Easyx实现扫雷游戏 2023-02-06
- C语言详解float类型在内存中的存储方式 2023-03-27
- C语言qsort()函数的使用方法详解 2023-04-26
- Qt计时器使用方法详解 2023-05-30
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- ubuntu下C/C++获取剩余内存 2023-09-18
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
