哪种方法表现更佳:.Any() vs .Count() > 0?

713
System.Linq 命名空间中,我们现在可以扩展 IEnumerable 以拥有 Any()Count() 的扩展方法。
最近我被告知,如果我想检查一个集合是否包含一个或多个项,我应该使用 .Any() 扩展方法而不是 .Count() > 0 扩展方法,因为 .Count() 扩展方法必须遍历所有的项。
其次,一些集合有一个属性(而不是扩展方法),叫做 CountLength。与 .Any().Count() 相比,使用它们会更好吗?
是 / 否?

最好在可枚举对象上使用Any(),在集合上使用Count()。如果有人觉得写'(somecollection.Count > 0)'会导致混淆或可读性问题,最好将其编写为扩展方法并命名为Any()。这样每个人都满意,无论是性能方面还是可读性方面。因此,您的所有代码都将具有一致性,项目中的各个开发人员不必担心选择Count vs Any。 - Mahesh Bongani
3
你可能见过Count() > 0和Any()的区别,但你见过Distinct().Count() > 1和Distinct().Skip(1).Any()的区别吗?对于大量项目的情况下,后者明显更快,因为Count()需要遍历整个集合才能得到数量。Skip(1).Any()可以避免全枚举。在一个包含1000个长度为1的字符串数组中进行100k次检查,Count() > 1需要大约4000ms,而Skip(1).Any()只需要20ms。 - Triynko
11个回答

-3

我创建了一个使用IList的示例应用程序,其中包含100个元素到100万个元素,以查看Count vs Any哪个更好。

代码

class Program
{
    static void Main()
    {

        //Creating List of customers
        IList<Customer> customers = new List<Customer>();
        for (int i = 0; i <= 100; i++)
        {
            Customer customer = new Customer
            {
                CustomerId = i,
                CustomerName = string.Format("Customer{0}", i)
            };
            customers.Add(customer);
        }

        //Measuring time with count
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        if (customers.Count > 0)
        {
            Console.WriteLine("Customer list is not empty with count");
        }
        stopWatch.Stop();
        Console.WriteLine("Time consumed with count: {0}", stopWatch.Elapsed);

        //Measuring time with any
        stopWatch.Restart();
        if (customers.Any())
        {
            Console.WriteLine("Customer list is not empty with any");
        }
        stopWatch.Stop();
        Console.WriteLine("Time consumed with count: {0}", stopWatch.Elapsed);
        Console.ReadLine();

    }
}

public class Customer
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
}

结果: 在此输入图像描述

任何一个都比计数好。


你正在比较 .Count.Any(),而使用这些微小的量只能测量写入控制台所需的时间,而这个时间在每次运行时都会有很大的差异。没有 Console.WriteLine 的调用,Count 更快,这确实不需要更多证据了。 - Gert Arnold
@RRaveen - 请查看 https://github.com/dotnet/BenchmarkDotNet,了解如何对C#代码进行一些漂亮的基准测试。这将对您有很大帮助! - Pure.Krome

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接