1. 程式人生 > >LINQ能不能用系列(一)LINQ to Object 效率比對

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

複製程式碼
/// <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)); }
複製程式碼