詳解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數(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耗時:" + watch.Elapsed.TotalMilliseconds); Console.WriteLine("Exists耗時:" + watch1.Elapsed.TotalMilliseconds); Console.WriteLine("Where耗時:" + watch2.Elapsed.TotalMilliseconds); Console.WriteLine("Any耗時:" + watch3.Elapsed.TotalMilliseconds); Console.ReadLine(); }
執(zhí)行結(jié)果如下圖所示
結(jié)論
通過上圖可以看出性能排序為
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# DataSet的內(nèi)容寫成XML時如何格式化字段數(shù)據(jù)
許多讀者經(jīng)常詢問一個問題,那就是在將DataSet的內(nèi)容寫成XML時,如何格式化字段數(shù)據(jù)。最常見的需求,就是希望日期時間值與數(shù)值數(shù)據(jù)能夠以所需的格式呈現(xiàn)于XML中。2009-02-02C#中的自動類型轉(zhuǎn)換和強制類型轉(zhuǎn)換
這篇文章主要介紹了C#中的自動類型轉(zhuǎn)換和強制類型轉(zhuǎn)換,非常不錯,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-08-08C#獲取路由器外網(wǎng)IP,MAC地址的實現(xiàn)代碼
這篇文章主要介紹了C#獲取路由器外網(wǎng)IP,MAC地址的實現(xiàn)代碼,需要的朋友可以參考下2016-11-11DevExpress之ChartControl實現(xiàn)餅狀圖百分比演示實例
這篇文章主要介紹了DevExpress之ChartControl實現(xiàn)餅狀圖百分比演示的方法,實例講述了窗體與圖形繪制函數(shù)的用法,需要的朋友可以參考下2014-10-10