判斷IEnumerable<T>有無資料時請用Any()少用Count(),筆數多效能差很大

  • 5988
  • 0

判斷IEnumerable<T>有無資料時請用Any()少用Count(),筆數多效能差很大啊!

dotBlogs 的標籤: , ,

前一篇文章:大量資料在做Linq比對時改用請注意轉型的效能問題,且考慮使用Lookup/Dictionary以提昇效能,依 91 大建議,我有做一個小修改:把程式碼中 if (resultItem.Count() > 0) 改成 if (resultItem.Any()) 效能會更好,而且的確如果只是要判斷 IEnumerable<T> 中有無資料,用 Any() 更名正言順。

這篇文章很簡單只是做效能的測試,分別測試 IEnumerable<T> 的 Count()、Any(),和 List 的 Count 屬性。

對了,關於 Count()、Any() 效能差異之原因,請參閱小朱大的文章:[.NET][LINQ] Any() vs. Count() 何時可用? 何時不可用?

以下是測試程式碼,我們會看到非常可怕的效能差異:


    dt.Rows.Count.Dump(@"資料筆數:");
    Stopwatch sw = new Stopwatch();
    int doCount = 0;
    var dataIEnum = dt.AsEnumerable();
    sw.Start();
    for (int i = 0; i < 50000; i++)
    {
        if (dataIEnum.Count() > 0 ) doCount++;
    }
    sw.Stop();
    Console.WriteLine ("Count() 耗費時間:" + sw.ElapsedMilliseconds / 1000d);
    sw.Reset();
    doCount = 0;
    sw.Start();
    for (int i = 0; i < 50000; i++)
    {
        if (dataIEnum.Any()) doCount++;
    }
    sw.Stop();
    Console.WriteLine ("Any() 耗費時間:" + sw.ElapsedMilliseconds / 1000d);
    List<DataRow> dataList = dataIEnum.ToList();
    sw.Reset();
    doCount = 0;
    sw.Start();
    for (int i = 0; i < 50000; i++)
    {
        if (dataList.Count > 0) doCount++;
    }
    sw.Stop();
    Console.WriteLine ("List.Count 耗費時間:" + sw.ElapsedMilliseconds / 1000d);
113947

事實勝於熊辯,能用 Count 屬性時,一定要用,若資料來源是 IEnumerable<T>,沒有 Count 屬性可用,請務必使用 Any() 方法(對,就是我這個笨腦袋,要牢牢記得啊!)。

感謝 91 大一番話點醒了我,也感謝小朱大清楚的說明。

--------
沒什麼特別的~
不過是一些筆記而已