c# - LINQ Count() until,这样效率更高吗?

标签 c# performance linq 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);
    }

甚至

    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 个时,最好使用您推荐的两种方法中的任何一种。对于这两者的相对性能,您必须按照其他人的建议对它们进行分析。

关于c# - LINQ Count() until,这样效率更高吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9627666/

相关文章:

c# - 我如何使用 LINQ 将这个父子对象模型投影到一个平面的单个对象中?

mysql - 我应该如何索引这个 MySQL 数据库?

algorithm - 尝试优化此算法/代码以计算 a 和 b 之间互质整数的最大子集

c# - 在 EF Core Migration 中设置级联删除时,它不会在数据库中强制执行吗?

c# - 使用 LINQ。有两个不同的列表。如何识别不匹配的对象

c# - 对实现接口(interface)的对象进行 LINQ 查询

c# - 使用 lambda 语法的 linq 连接运算符类型

.net - 如何在 LINQ 中预加载整个 SQL 表?

c# - 带有 DWM : how to handle WM_NCCALCSIZE correctly 的自定义窗框

java - AJAX/JavaScript 搜索性能优于 Java/Oracle