bev*_*qua 11 c# linq performance ienumerable micro-optimization
假设我想检查集合中是否至少有N个元素.
这比做好吗?
Count() >= N
使用:
public static bool AtLeast<T>(this IEnumerable<T> enumerable, int max)
{
int count = 0;
return enumerable.Any(item => ++count >= max);
}
Run Code Online (Sandbox Code Playgroud)
甚至
public static bool Equals<T>(this IEnumerable<T> enumerable, int amount)
{
return enumerable.Take(amount).Count() == amount;
}
Run Code Online (Sandbox Code Playgroud)
我怎么能对此进行基准测试
/// <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;
}
Run Code Online (Sandbox Code Playgroud)
该.Count()方法内置了一些记录良好的优化.具体来说,如果你的枚举是一个ICollection,.Count()将是一个恒定时间操作,因为它将使用ICollection的.Count属性.
但是,在一般情况下,它将迭代整个IEnumerable以获得计数.如果你没有ICollection,当你有超过N个元素时,你最好使用两种建议的方法.对于这两者的相对表现,你必须像其他人建议的那样对它们进行分析.
| 归档时间: |
|
| 查看次数: |
1584 次 |
| 最近记录: |