C#for-loop和Array.Fill之间的性能差异

Mar*_*und 6 .net c# arrays performance benchmarkdotnet

我使用以下方法实现了以下基准BenchmarkDotNet:

public class ForVsFillVsEnumerable
{
    private bool[] data;

    [Params(10, 100, 1000)]
    public int N;

    [GlobalSetup]
    public void Setup()
    {
        data = new bool[N];
    }

    [Benchmark]
    public void Fill()
    {
        Array.Fill(data, true);
    }

    [Benchmark]
    public void For()
    {           
        for (int i = 0; i < data.Length; i++)
        {
            data[i] = true;
        }
    }

    [Benchmark]
    public void EnumerableRepeat()
    {
        data = Enumerable.Repeat(true, N).ToArray();
    }
}
Run Code Online (Sandbox Code Playgroud)

结果是:

BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17763.195 (1809/October2018Update/Redstone5)
Intel Core i7-8700K CPU 3.70GHz (Coffee Lake), 1 CPU, 12 logical and 6 physical cores
.NET Core SDK=2.2.200-preview-009648
  [Host] : .NET Core 2.2.0 (CoreCLR 4.6.27110.04, CoreFX 4.6.27110.04), 64bit RyuJIT
  Core   : .NET Core 2.2.0 (CoreCLR 4.6.27110.04, CoreFX 4.6.27110.04), 64bit RyuJIT

Job=Core  Runtime=Core
           Method |    N |       Mean |      Error |      StdDev |     Median | Ratio | Rank |
----------------- |----- |-----------:|-----------:|------------:|-----------:|------:|-----:|
             Fill |   10 |   3.675 ns |  0.2550 ns |   0.7150 ns |   3.331 ns |  1.00 |    1 |
                  |      |            |            |             |            |       |      |
              For |   10 |   6.615 ns |  0.3928 ns |   1.1581 ns |   6.056 ns |  1.00 |    1 |
                  |      |            |            |             |            |       |      |
 EnumerableRepeat |   10 |  25.388 ns |  1.0451 ns |   2.9307 ns |  24.170 ns |  1.00 |    1 |
                  |      |            |            |             |            |       |      |
             Fill |  100 |  50.557 ns |  2.0766 ns |   6.1229 ns |  46.690 ns |  1.00 |    1 |
                  |      |            |            |             |            |       |      |
              For |  100 |  64.330 ns |  4.0058 ns |  11.8111 ns |  59.442 ns |  1.00 |    1 |
                  |      |            |            |             |            |       |      |
 EnumerableRepeat |  100 |  81.784 ns |  4.2407 ns |  12.5039 ns |  75.937 ns |  1.00 |    1 |
                  |      |            |            |             |            |       |      |
             Fill | 1000 | 447.016 ns | 15.4420 ns |  45.5312 ns | 420.239 ns |  1.00 |    1 |
                  |      |            |            |             |            |       |      |
              For | 1000 | 589.243 ns | 51.3450 ns | 151.3917 ns | 495.177 ns |  1.00 |    1 |
                  |      |            |            |             |            |       |      |
 EnumerableRepeat | 1000 | 519.124 ns | 21.3580 ns |  62.9746 ns | 505.573 ns |  1.00 |    1 |
Run Code Online (Sandbox Code Playgroud)

最初我猜测它Array.Fill做了一些优化,使它比for-loop 表现更好,但后来我检查了.NET Core源代码,看看Array.Fill实现非常简单:

public static void Fill<T>(T[] array, T value)
{
    if (array == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
    }

    for (int i = 0; i < array.Length; i++)
    {
        array[i] = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

性能足够接近,但它看起来Fill仍然有点快,for即使在引擎盖下它是完全相同的代码.你能解释一下原因吗?或者我只是错误地阅读结果?

Adr*_*tti 12

我很惊讶Enumerable.Repeat(),与我的第一个想法相反,它很好地扩展.无论如何,要回答你的问题:当你使用时,你For()在重复访问一个类成员时,Array.Fill()只需要一次获得它的地址.

我更惊讶的是编译器没有检测到 - 并优化 - 这只是为了读取你需要ldarg.0获取其值的类成员的值,this然后ldfld ForVsFillVsEnumerable.data获取它的实际地址.在ForVsFillVsEnumerable.Fill()这只做一次电话Array.Fill().

你可以检查这个写你自己的填充功能:

[Benchmark]
public void For2()
{
    ForImpl(data);
}

private static void ForImpl(bool[] data)
{
    for (int i = 0; i < data.Length; i++)
    {
        data[i] = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

注1:无论性能,使用的库函数总是更好,因为它可能未来优化的利益(他们可以决定,例如,添加特定的重载Array.Fill()和本地代码来实现他们在那里-对于某些架构-一个普通的memset()是非常快的).

注2:如果循环代码太小(而且速度快),我会避免用小矢量(10或100项)来测量任何东西,因为设置一个合适的测试环境以可靠地测量几纳秒的差异是非常困难的.我认为1000(或甚至100,000)是最小的开始(即使在那种情况下,许多其他东西也会起到相关的作用......)除非你的真实用例是10/100 ......那种情况我会尝试测量一个更大的算法,这个差异更明显(如果不是那么你就不应该关心).