首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >IEnumerable.Count()或ToList().Count

IEnumerable.Count()或ToList().Count
EN

Stack Overflow用户
提问于 2015-10-14 14:03:18
回答 3查看 13.4K关注 0票数 9

我得到了我自己的类的对象列表,如下所示:

代码语言:javascript
运行
复制
public class IFFundTypeFilter_ib
{
    public string FundKey { get; set; }
    public string FundValue { get; set; }
    public bool IsDisabled { get; set; }
}

通过执行查询collection.Where(some condition)并计算匹配对象的数量来设置属性IsDisabled。结果是IEnumarable<IFFundTypeFilter_ib>,它不包含属性计数。我在想,什么会更快。

这一条:

代码语言:javascript
运行
复制
collection.Where(somecondition).Count();

或者这个:

代码语言:javascript
运行
复制
collection.Where(someocondition).ToList().Count;

集合可以包含很少的对象,但也可以包含,例如700。我将在其他条件下进行两次计数呼叫。在第一个条件中,我检查FundKey是否等于某个键,在第二个条件中,我执行相同的操作,但我将其与其他键值进行比较。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-10-14 16:47:04

你问:

我想知道,什么会更快。

无论何时你问你是否应该计时,并找出答案。

我开始测试所有这些获取计数的变体:

代码语言:javascript
运行
复制
var enumerable = Enumerable.Range(0, 1000000);
var list = enumerable.ToList();

var methods = new Func<int>[]
{
    () => list.Count,
    () => enumerable.Count(),
    () => list.Count(),
    () => enumerable.ToList().Count(),
    () => list.ToList().Count(),
    () => enumerable.Select(x => x).Count(),
    () => list.Select(x => x).Count(),
    () => enumerable.Select(x => x).ToList().Count(),
    () => list.Select(x => x).ToList().Count(),
    () => enumerable.Where(x => x % 2 == 0).Count(),
    () => list.Where(x => x % 2 == 0).Count(),
    () => enumerable.Where(x => x % 2 == 0).ToList().Count(),
    () => list.Where(x => x % 2 == 0).ToList().Count(),
};

我的测试代码显式地运行每个方法1,000次,使用Stopwatch测量每个执行时间,并忽略发生垃圾收集的所有结果。然后,它会得到每个方法的平均执行时间。

代码语言:javascript
运行
复制
var measurements =
    methods
        .Select((m, i) => i)
        .ToDictionary(i => i, i => new List<double>());

for (var run = 0; run < 1000; run++)
{
    for (var i = 0; i < methods.Length; i++)
    {
        var sw = Stopwatch.StartNew();
        var gccc0 = GC.CollectionCount(0);
        var r = methods[i]();
        var gccc1 = GC.CollectionCount(0);
        sw.Stop();
        if (gccc1 == gccc0)
        {
            measurements[i].Add(sw.Elapsed.TotalMilliseconds);
        }
    }
}

var results =
    measurements
        .Select(x => new
        {
            index = x.Key,
            count = x.Value.Count(),
            average = x.Value.Average().ToString("0.000")
        });

以下是结果(从最慢到最快排序):

代码语言:javascript
运行
复制
+---------+-----------------------------------------------------------+
| average |                          method                           |
+---------+-----------------------------------------------------------+
| 14.879  | () => enumerable.Select(x => x).ToList().Count(),         |
| 14.188  | () => list.Select(x => x).ToList().Count(),               |
| 10.849  | () => enumerable.Where(x => x % 2 == 0).ToList().Count(), |
| 10.080  | () => enumerable.ToList().Count(),                        |
| 9.562   | () => enumerable.Select(x => x).Count(),                  |
| 8.799   | () => list.Where(x => x % 2 == 0).ToList().Count(),       |
| 8.350   | () => enumerable.Where(x => x % 2 == 0).Count(),          |
| 8.046   | () => list.Select(x => x).Count(),                        |
| 5.910   | () => list.Where(x => x % 2 == 0).Count(),                |
| 4.085   | () => enumerable.Count(),                                 |
| 1.133   | () => list.ToList().Count(),                              |
| 0.000   | () => list.Count,                                         |
| 0.000   | () => list.Count(),                                       |
+---------+-----------------------------------------------------------+

这里有两件重要的事情。

首先,任何具有.ToList()内联的方法都比没有它的等效方法慢得多。

第二,LINQ运算符在可能的情况下利用可枚举的基础类型来简化计算。enumerable.Count()list.Count()方法显示了这一点。

list.Countlist.Count()调用之间没有区别。所以关键的比较是在enumerable.Where(x => x % 2 == 0).Count()enumerable.Where(x => x % 2 == 0).ToList().Count()调用之间。由于后者包含一个额外的操作,我们预计它会花费更长的时间。它几乎长了2.5毫秒。

我不知道您为什么说要调用计数代码两次,但如果您这样做了,最好还是构建列表。如果不是这样,那就在查询之后执行普通的.Count()调用。

票数 22
EN

Stack Overflow用户

发布于 2015-10-14 14:21:53

通常,物化到列表的效率会较低。

此外,如果使用两个条件,则缓存结果或将查询物化到List是没有意义的。

您应该只使用Count的重载,它接受一个谓词:

代码语言:javascript
运行
复制
collection.Count(someocondition);

正如@CodeCaster在评论中提到的那样,它等同于collection.Where(condition).Count(),但更具可读性和简洁性。

票数 4
EN

Stack Overflow用户

发布于 2015-10-14 14:25:40

以这种方式使用它

代码语言:javascript
运行
复制
var count = collection.Where(somecondition).ToList().Count;

仅仅为了获得计数而填充列表是没有意义的,所以对于这种情况,使用IEnumerable<T>.Count()是合适的方式。

在执行以下操作的情况下,使用ToList是有意义的

代码语言:javascript
运行
复制
var list = collection.Where(somecondition).ToList();
var count = list.Count;
// do something else with the list
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33117732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档