新聞中心
這里我們對LINQ中LIST

#T#
***:在.NET 1.1時,我還有很多和我一樣的程序員,都會常用到ArrayList,當(dāng)時要想對這種集合元素進(jìn)行查找,大多會采用for循環(huán)來完成,當(dāng)然也可以采用BinarySearch 方法。但自從有了.NET 2.0以及.NET 3.5后,ArrayList就已經(jīng)很少使用了,大家都認(rèn)為List
- public class Person
- {
- public string firstName
- { get; set; }
- public string lastName
- { get; set; }
- public int ID
- { get; set; }
- }
先構(gòu)造一個Person的泛型集合。當(dāng)然一般情況下不會有這樣的大集合,但為了比較不同方法的搜索性能,這是有必要的。
- List
list = new List (); - for (int i = 0; i < 100001; i++)
- {
- Person p = new Person();
- p.firstName = i.ToString() + "firstName";
- p.lastName = i.ToString() + "lastName";
- list.Add(p);
- }
1:List
- public class FindPerson
- {
- public string firstName;
- public FindPerson(string _firstName)
- { this.firstName = _firstName; }
- public bool PersonPredicate(Person p)
- {
- return p.ID >= 50000;
- }
- }
- Stopwatch sw = new Stopwatch();
- sw.Start();
- List
persons = list.FindAll(new Predicate (fp.PersonPredicate)); - sw.Stop();
- Response.Write("Find方法搜索用時" + sw.ElapsedMilliseconds.ToString() + "
");
2:傳統(tǒng)的for循環(huán)。
- sw.Start();
- List
newPersons = new List (); - for (int j = 0; j < list.Count; j++)
- {
- if (list[j].ID >= 50000)
- {
- newPersons.Add(list[j]);
- }
- }
- sw.Stop();
- Response.Write("for循環(huán)搜索用時" + sw.ElapsedMilliseconds.ToString() + "
");
3:LINQ方式查詢。
- sw = new Stopwatch();
- sw.Start();
- var pn = (from m in list
- where m.ID >=50000
- select m).ToList
(); - sw.Stop();
- Response.Write("linq搜索用時" + sw.ElapsedMilliseconds.ToString() + "
");
輸出結(jié)果:雖然用時差不多,但還是傳統(tǒng)的for循環(huán)性能***,盡管寫法上并無新意。FindAll我覺的有一點(diǎn)比較好的就是,如果針對List
Find方法搜索用時5
for循環(huán)搜索用時4
linq搜索用時6
第二:再來看對List
1:Sort。這里先寫一個自定義的比較類PersonComparer
- public class PersonComparer : IComparer
- {
- public int Compare(Person x, Person y)
- {
- return x.ID.CompareTo(y.ID);
- }
- }
排序代碼:
- sw = new Stopwatch();
- sw.Start();
- list.Sort(new PersonComparer());
- sw.Stop();
- Response.Write("Sort排序用時" + sw.ElapsedMilliseconds.ToString() + "
");
2:Linq方式。
- sw = new Stopwatch();
- sw.Start();
- var pn = (from m in list
- orderby m.ID descending
- select m).ToList
(); - sw.Stop();
- Response.Write("linq排序用時" + sw.ElapsedMilliseconds.ToString() + "
");
輸出結(jié)果:在排序上linq還是占有比較大的優(yōu)勢。
Sort排序用時670
linq排序用時195
總結(jié)
對于泛型集合的操作,并不能一味的說某種方式有絕對的優(yōu)勢,需要根據(jù)對應(yīng)的情景來選擇不同的處理方式。有時候最常見的最簡單的也許是性能***的。新技術(shù)當(dāng)然有它的優(yōu)點(diǎn), Linq提供的排序在性能上就有明顯的優(yōu)勢,但在查詢方面也是最差的,盡管差距不大。
未解問題:
至于為什么for循環(huán)在查詢時性能***,LINQ在排序上為什么性能好,本人并不知道其中原因,如有知道的朋友,請指教。
網(wǎng)站標(biāo)題:對比List<T>搜索和排序中不同方法的性能
網(wǎng)頁地址:http://fisionsoft.com.cn/article/cogojod.html


咨詢
建站咨詢
