LINQ能不能用系列(一)數(shù)組篩選效率對(duì)比
相信LINQ大家已經(jīng)很熟悉了,如果有不太熟的,可以參考MSDN 地址:http://msdn.microsoft.com/zh-cn/library/bb397933.aspx
緣由:LINQ到底能不能用?究竟好不好用,很多時(shí)候大家還是眾說紛紜,有人迷茫,有人觀望,有人覺得無(wú)所謂,或者還有人說只是語(yǔ)法糖,中看不中用,哪我們這個(gè)系列就為大家揭開謎團(tuán)。首先來(lái)看Linq在數(shù)組篩選方面的效率測(cè)試吧。
實(shí)例分析
測(cè)試環(huán)境:Visual Studio 2011 Beta(netframework 4.0+)C# 控制臺(tái)程序
測(cè)試需求:從10000000條數(shù)據(jù)中查詢大于100的數(shù)據(jù)。
核心代碼(LINQ):
- var linqList = from num in list1
 - where num > 100
 - select num;
 
完整代碼(根據(jù)園友意見以調(diào)整):
- /// <summary>
 - /// 效率測(cè)試
 - /// </summary>
 - /// <param name="testCount">第幾次測(cè)試</param>
 - private static void timeTest(int testCount)
 - {
 - const int listCount = 10000000; // 數(shù)組長(zhǎng)度
 - Random random = new Random(); // 數(shù)據(jù)隨機(jī)構(gòu)建值
 - // 數(shù)組構(gòu)建
 - List<int> listData = new List<int>();
 - for (int i = 0; i < listCount; i++)
 - {
 - listData.Add(random.Next(10000));
 - }
 - // LINQ 測(cè)試
 - Stopwatch linq_Stopwatch = new Stopwatch();
 - linq_Stopwatch.Start();
 - var linqList = from num in listData
 - where num > 100
 - select num;
 - var linqCount = linqList.Count();
 - linq_Stopwatch.Stop();
 - // 普通方式 測(cè)試
 - Stopwatch before_Stopwatch = new Stopwatch();
 - before_Stopwatch.Start();
 - List<int> beforeList = new List<int>(listCount);
 - for (int i = 0; i < listData.Count(); i++)
 - {
 - if (listData[i] > 100)
 - beforeList.Add(listData[i]);
 - }
 - var beforeCount = beforeList.Count;
 - before_Stopwatch.Stop();
 - // 打印結(jié)果
 - Console.WriteLine(String.Format("第{0}次測(cè)試,測(cè)試:{5}條數(shù)據(jù)。\n\r \t LINQ用時(shí):{1}毫秒,篩選了{(lán)2}條數(shù)據(jù)。\n\r\t 普通用時(shí):{3}毫秒,篩選了{(lán)4}條數(shù)據(jù)。\r\n",
 - testCount, linq_Stopwatch.ElapsedMilliseconds, linqCount, before_Stopwatch.ElapsedMilliseconds, beforeCount, listCount));
 - }
 
結(jié)果

結(jié)論:由此可知數(shù)據(jù)篩選,LINQ效率遠(yuǎn)遠(yuǎn)大于之前用的手工篩選。如此LINQ不但語(yǔ)法簡(jiǎn)潔優(yōu)雅,而且效率也遠(yuǎn)遠(yuǎn)勝出,所有數(shù)據(jù)篩選LINQ可用。
原文鏈接:http://www.cnblogs.com/stone_w/archive/2012/05/08/2490440.html
 【編輯推薦】















 
 
 








 
 
 
 