LINQ能不能用系列(一)LINQ to Object 效率比對

前言

簡介:LINQ,語言集成查詢(Language INtegrated Query)是一組用於c#和Visual Basic語言的擴展。

分類:LINQ to Object, LINQ to XML, LINQ to SQL, LINQ to DataSet,LINQ to ADO.NET。

相關:相信linq大家已經很熟悉了,如果有不太熟的,可以參考MSDN 地址:http://msdn.microsoft.com/zh-cn/library/bb397933.aspx
緣由:Linq 到底能不能用?究竟好不好用,很多時候大家還是衆說紛紜,有人迷茫,有人觀望,有人覺得無所謂,或者還有人說只是語法糖,中看不中用,哪我們這個系列就爲大家揭開謎團。首先來看LINQ to Object在數組篩選方面的效率測試吧。

實例分析

測試環境: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 to Object在做數據處理,效率要好於手動判斷,當然LINQ偉大應該是她的語法簡潔與優雅。在做數據處理時個人推薦使用LINQ to Object!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章