LINQ能不能用系列(一)數組篩選效率對比
相信LINQ大家已經很熟悉了,如果有不太熟的,可以參考MSDN 地址:http://msdn.microsoft.com/zh-cn/library/bb397933.aspx
緣由:LINQ到底能不能用?究竟好不好用,很多時候大家還是眾說紛紜,有人迷茫,有人觀望,有人覺得無所謂,或者還有人說只是語法糖,中看不中用,哪我們這個系列就為大家揭開謎團。首先來看Linq在數組篩選方面的效率測試吧。
實例分析
測試環境:Visual Studio 2011 Beta(netframework 4.0+)C# 控制臺程序
測試需求:從10000000條數據中查詢大于100的數據。
核心代碼(LINQ):
- var linqList = from num in list1
- where num > 100
- select num;
完整代碼(根據園友意見以調整):
- /// <summary>
- /// 效率測試
- /// </summary>
- /// <param name="testCount">第幾次測試</param>
- private static void timeTest(int testCount)
- {
- const int listCount = 10000000; // 數組長度
- Random random = new Random(); // 數據隨機構建值
- // 數組構建
- List<int> listData = new List<int>();
- for (int i = 0; i < listCount; i++)
- {
- listData.Add(random.Next(10000));
- }
- // LINQ 測試
- 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();
- // 普通方式 測試
- 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();
- // 打印結果
- Console.WriteLine(String.Format("第{0}次測試,測試:{5}條數據。\n\r \t LINQ用時:{1}毫秒,篩選了{2}條數據。\n\r\t 普通用時:{3}毫秒,篩選了{4}條數據。\r\n",
- testCount, linq_Stopwatch.ElapsedMilliseconds, linqCount, before_Stopwatch.ElapsedMilliseconds, beforeCount, listCount));
- }
結果
結論:由此可知數據篩選,LINQ效率遠遠大于之前用的手工篩選。如此LINQ不但語法簡潔優雅,而且效率也遠遠勝出,所有數據篩選LINQ可用。
原文鏈接:http://www.cnblogs.com/stone_w/archive/2012/05/08/2490440.html
【編輯推薦】