C# for 循环和 Array.Fill 之间的性能差异

Performance difference between C# for-loop and Array.Fill

我已经使用 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();
    }
}

结果是:

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 |

最初我猜 Array.Fill 做了一些优化,使其性能优于 for 循环,但后来我检查了 .NET Core source code 发现 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;
    }
}

性能足够接近,但似乎 Fill 始终比 for 快一点,即使在引擎盖下它是完全相同的代码。你能解释为什么吗?或者我只是错误地阅读了结果?

我对 Enumerable.Repeat() 感到惊讶,这与我最初的想法相反,它的扩展性非常好。无论如何,回答你的问题:当你使用 For() 时你重复访问一个 class 成员,而当调用 Array.Fill() 时你只获得它的地址一次。

令我更惊讶的是,编译器没有检测到并优化它,但要读取 class 成员的值,您需要 ldarg.0 来获取 [=15= 的值] 然后 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;
    }
}

注 1:无论性能如何,使用库函数总是更好,因为它可能会受益于未来的优化(例如,他们可能决定为 Array.Fill() 添加特定的重载并使用本机代码 - 对于某些架构 - 普通 memset() 非常快)。

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