[英]LINQ Count() until, is this more efficient?
假設我想檢查集合中是否至少有N個元素。
這比做好嗎?
Count() >= N
使用:
public static bool AtLeast<T>(this IEnumerable<T> enumerable, int max)
{
int count = 0;
return enumerable.Any(item => ++count >= max);
}
甚至
public static bool Equals<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount).Count() == amount;
}
我怎么能對此進行基准測試
/// <summary>
/// Returns whether the enumerable has at least the provided amount of elements.
/// </summary>
public static bool HasAtLeast<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount).Count() == amount;
}
/// <summary>
/// Returns whether the enumerable has at most the provided amount of elements.
/// </summary>
public static bool HasAtMost<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount + 1).Count() <= amount;
}
在.Count()
方法中內置了一些記錄良好的優化。 具體來說,如果你的枚舉是一個ICollection
, .Count()
將是一個常量操作,因為它將使用ICollection
的.Count
屬性。
但是,在一般情況下,它將迭代整個IEnumerable
以獲取計數。 如果你沒有ICollection
,當你有超過N個元素時,你最好使用兩種建議的方法。 對於這兩者的相對表現,你必須像其他人建議的那樣對它們進行分析。
var list = Enumerable.Range(1, 1000000);
var t = new Stopwatch();
t.Restart();
var count = list.Count() > 100000;
t.Stop();
PrintTime(t, count);
t.Restart();
var atLeast = list.AtLeast(100000);
t.Stop();
PrintTime(t, atLeast);
t.Restart();
var equals = list.Equalss(100000);
t.Stop();
PrintTime(t, equals);
PrintTime()打印出計時器滴答的結果:
True 20818
True 8774
True 8688
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.