【问题标题】:Why LINQ method Any does not check Count?为什么 LINQ 方法 Any 不检查 Count?
【发布时间】:2018-04-05 02:04:32
【问题描述】:

如果我们查看扩展方法Any 的源代码,我们会发现它总是使用枚举器:

public static bool Any<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
        throw Error.ArgumentNull(nameof (source));
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        if (enumerator.MoveNext())
            return true;
    }
    return false;
}

我认为,如果集合是 IList 就像在 SingleOrDefault 方法中一样,检查 Count 属性不是更好(对于性能):

public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
        throw Error.ArgumentNull(nameof(source));
    IList<TSource> sourceList = source as IList<TSource>;
    if (sourceList != null)
    {
        switch (sourceList.Count)
        {
            case 0:
                return default(TSource);
            case 1:
                return sourceList[0];
        }
    }
    else
    {
        //...
    }
    throw Error.MoreThanOneElement();
}

我说,它可以是这样的:

private static bool Any<TSource>(IEnumerable<TSource> source)
{
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    IList<TSource> sourceList = source as IList<TSource>;

    if (sourceList != null)
    {
        return sourceList.Count != 0;
    }

    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        if (enumerator.MoveNext())
            return true;
    }
    return false;
}

我写了一个基准测试它:

namespace AnyTests
{

    class Program
    {
        static void Main(string[] args)
        {
            BenchmarkRunner.Run<Test>();
        }
    }

    public class Test
    {
        private readonly List<int> list1 = new List<int>(new[] { 1, 2, 3, 4, 5 });

        private readonly IEnumerable<int> list2 = GetCollection();

        private static IEnumerable<int> GetCollection()
        {
            yield return 1;
        }

        [Benchmark]
        public void TestLinqAnyList()
        {
            Enumerable.Any(list1);
        }

        [Benchmark]
        public void TestNewAnyList()
        {
            NewAny(list1);
        }

        [Benchmark]
        public void TestLinqAnyEnumerable()
        {
            Enumerable.Any(list2);
        }

        [Benchmark]
        public void TestNewAnyEnumerable()
        {
            NewAny(list2);
        }


        private static bool NewAny<TSource>(IEnumerable<TSource> source)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            IList<TSource> sourceList = source as IList<TSource>;

            if (sourceList != null)
            {
                return sourceList.Count != 0;
            }

            using (IEnumerator<TSource> enumerator = source.GetEnumerator())
            {
                if (enumerator.MoveNext())
                    return true;
            }
            return false;
        }
    }
}

结果显示大约好两倍:

// * Summary *

BenchmarkDotNet=v0.10.13, OS=Windows 10 Redstone 3 [1709, Fall Creators Update] (10.0.16299.192)
Intel Core i7-7700 CPU 3.60GHz (Kaby Lake), 1 CPU, 8 logical cores and 4 physical cores
Frequency=3515624 Hz, Resolution=284.4445 ns, Timer=TSC
  [Host]     : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.2600.0
  DefaultJob : .NET Framework 4.7.1 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.2600.0


                Method |     Mean |     Error |    StdDev |
---------------------- |---------:|----------:|----------:|
       TestLinqAnyList | 26.80 ns | 0.1382 ns | 0.1154 ns |
        TestNewAnyList | 12.75 ns | 0.0480 ns | 0.0426 ns |
 TestLinqAnyEnumerable | 18.03 ns | 0.0947 ns | 0.0886 ns |
  TestNewAnyEnumerable | 23.51 ns | 0.0913 ns | 0.0762 ns |

IList 大约好两倍,IEnumerable 大约差 20%。

那么,问题是:在SingleOrDefault 方法中使用优化而不在Any 中使用它的原因是什么?

【问题讨论】:

  • .net 核心存储库中有一个关于此的问题:github.com/dotnet/corefx/issues/23700。您可以在那里阅读有关其优点和缺点的第一手信息(特别是 Jon Hannas 的评论)。您会发现一些令人惊讶的事情,例如对于数组 - 当前版本实际上比检查 ICollection.Count 更快(而对于列表则要慢一些)。

标签: c# .net linq


【解决方案1】:

您的问题背后的假设可能是:

计数很快,为什么不用呢?

为什么Any 不使用它的一个合理答案是Count 并不总是快。他们选择的实现的优点是它将具有相对稳定和低成本(即大致O(1))。 然而,在所有情况下它可能都没有Count 快(正如你所确定的那样)。

没有保证实现IListICollection 的类将具有快速 Count 属性。 例如,ConcurrentDictionary 对于Count &gt; 0 的执行速度通常比现有的Any 实现要慢。

此外,您使用 IList 的代码可能应该使用 ICollection,因为您的代码不需要 IList 提供访问权限的额外功能。

【讨论】:

  • 正确。 LINQ 是为 IEnumerable 而不是 IList 构建的。但是我认为支持 .NET 框架中最常见的集合类是微不足道的。
  • 在一个框架中,唉,每一件事都是微不足道的。 :(blogs.msdn.microsoft.com/ericgu/2004/01/12/minus-100-points
  • 但无论如何,SingleOrDefault 使用Count。为什么,如果它可以很慢?只是不明白哪些地方可以使用“慢”方法,哪些地方不可以
  • 是的,这意味着 SingleOrDefault 对于任何实现 IList 并且具有慢速 Count 属性 @Backs 的类型都会很慢。 LINQ 的本质是它是一个略微泄漏的抽象——对于他们正在权衡的每种方法。他们得到的权衡是“正确的”,有时是“错误的”(例如stackoverflow.com/a/47631641/34092)。很难构建这种东西,因为接口(@98​​7654343@、ICollection 或其他)告诉您某事是否可能,而不是其性能成本。现有Any的好处是成本比较稳定。
  • @mjwills 我写了一篇关于这个问题的小帖子:blog.rogatnev.net/2018/06/16/Any-vs-Count.html
猜你喜欢
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 2016-08-04
相关资源
最近更新 更多