詳解C# List<T>的Contains,Exists,Any,Where性能對比
測試
新建一個(gè)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數(shù)據(jù)
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耗時(shí):" + watch.Elapsed.TotalMilliseconds);
Console.WriteLine("Exists耗時(shí):" + watch1.Elapsed.TotalMilliseconds);
Console.WriteLine("Where耗時(shí):" + watch2.Elapsed.TotalMilliseconds);
Console.WriteLine("Any耗時(shí):" + watch3.Elapsed.TotalMilliseconds);
Console.ReadLine();
}
執(zhí)行結(jié)果如下圖所示

結(jié)論
通過上圖可以看出性能排序?yàn)?br />
Contains > Exists > Where > Any
注意:
Contains中不能帶查詢條件
到此這篇關(guān)于詳解C# List<T>的Contains,Exists,Any,Where性能對比的文章就介紹到這了,更多相關(guān)C# Contains,Exists,Any,Where內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#操作DataGridView獲取或設(shè)置當(dāng)前單元格的內(nèi)容
這篇文章介紹了C#操作DataGridView獲取或設(shè)置當(dāng)前單元格的內(nèi)容,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02
C#TreeView 無限級別分類實(shí)現(xiàn)方法
2013-04-04
一個(gè)可攜帶附加消息的增強(qiáng)消息框MessageBoxEx
一個(gè)可攜帶附加消息的增強(qiáng)消息框MessageBoxEx分享給大家,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
Winform界面中實(shí)現(xiàn)通用工具欄按鈕的事件處理方法
下面小編就為大家分享一篇Winform界面中實(shí)現(xiàn)通用工具欄按鈕的事件處理方法,具有很好的參考價(jià)值,希望對大家有所幫助2017-11-11
DevExpress之ChartControl用法實(shí)例總結(jié)
這篇文章主要介紹了DevExpress之ChartControl用法實(shí)例總結(jié),需要的朋友可以參考下2014-08-08
C#實(shí)現(xiàn)給PDF文檔設(shè)置過期時(shí)間
我們可以給一些重要文檔或者臨時(shí)文件設(shè)置過期時(shí)間和過期信息提示來提醒讀者或管理者文檔的時(shí)效性,并及時(shí)對文檔進(jìn)行調(diào)整、更新等。下面本文將介紹如何通過C#來給PDF文檔設(shè)置過期時(shí)間的方法。需要的可以參考一下2022-01-01
使用數(shù)字簽名實(shí)現(xiàn)數(shù)據(jù)庫記錄防篡改(Java實(shí)現(xiàn))
本文主要介紹了Java中使用數(shù)字簽名實(shí)現(xiàn)數(shù)據(jù)庫記錄防篡改的方法與步驟。具有很好的參考價(jià)值,下面跟著小編一起來看下吧2017-01-01

