詳解C# List<T>的Contains,Exists,Any,Where性能對(duì)比
測(cè)試
新建一個(gè)Person類(lèi)
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); //下面通過(guò)三種方法判斷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é)論
通過(guò)上圖可以看出性能排序?yàn)?br />
Contains > Exists > Where > Any
注意:
Contains中不能帶查詢(xún)條件
到此這篇關(guān)于詳解C# List<T>的Contains,Exists,Any,Where性能對(duì)比的文章就介紹到這了,更多相關(guān)C# Contains,Exists,Any,Where內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# DataSet的內(nèi)容寫(xiě)成XML時(shí)如何格式化字段數(shù)據(jù)
許多讀者經(jīng)常詢(xún)問(wèn)一個(gè)問(wèn)題,那就是在將DataSet的內(nèi)容寫(xiě)成XML時(shí),如何格式化字段數(shù)據(jù)。最常見(jiàn)的需求,就是希望日期時(shí)間值與數(shù)值數(shù)據(jù)能夠以所需的格式呈現(xiàn)于XML中。2009-02-02C# newtonsoft.json中文亂碼問(wèn)號(hào)的解決方案
這篇文章主要介紹了C# newtonsoft.json中文亂碼問(wèn)號(hào)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07C# 中SharpMap的簡(jiǎn)單使用實(shí)例詳解
SharpMap是一個(gè)基于.net 2.0使用C#開(kāi)發(fā)的Map渲染類(lèi)庫(kù),可以渲染各類(lèi)GIS數(shù)據(jù)(目前支持ESRI Shape和PostGIS格式),可應(yīng)用于桌面和Web程序,具體內(nèi)容詳情大家參考下本文吧2017-08-08C#開(kāi)發(fā)中經(jīng)常用的加密解密方法示例
這篇文章主要給大家介紹了關(guān)于C#開(kāi)發(fā)中經(jīng)常用的加密解密方法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用C#具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07C#中的自動(dòng)類(lèi)型轉(zhuǎn)換和強(qiáng)制類(lèi)型轉(zhuǎn)換
這篇文章主要介紹了C#中的自動(dòng)類(lèi)型轉(zhuǎn)換和強(qiáng)制類(lèi)型轉(zhuǎn)換,非常不錯(cuò),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-08-08如何獲取C#中方法的執(zhí)行時(shí)間以及其代碼注入詳解
這篇文章主要給大家介紹了關(guān)于如何獲取C#中方法的執(zhí)行時(shí)間以及其代碼注入的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧2018-11-11C#獲取路由器外網(wǎng)IP,MAC地址的實(shí)現(xiàn)代碼
這篇文章主要介紹了C#獲取路由器外網(wǎng)IP,MAC地址的實(shí)現(xiàn)代碼,需要的朋友可以參考下2016-11-11DevExpress之ChartControl實(shí)現(xiàn)餅狀圖百分比演示實(shí)例
這篇文章主要介紹了DevExpress之ChartControl實(shí)現(xiàn)餅狀圖百分比演示的方法,實(shí)例講述了窗體與圖形繪制函數(shù)的用法,需要的朋友可以參考下2014-10-10