I have implemented the following benchmark using 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();
}
}
The results are:
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 |
Originally I guessed the Array.Fill
does some optimizations which make it perform better than for
-loop, but then I checked the .NET Core source code to see that the Array.Fill
implementation is pretty straightforward:
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;
}
}
The performance is close enough, but it stills seems Fill
is consistently a bit faster then for
even though under the hood it is exactly the same code. Can you explain why? Or am I just reading the results incorrectly?