C# .NET Performance - Initialising Empty Array

When initialising an empty array in your codebase, there are two options you would choose from: new T[0] or Array.Empty<T>(). This benchmark is to compare the two options to see their performance statistics.

Benchmark and Results

[SimpleJob(RuntimeMoniker.CoreRt50)]
[SimpleJob(RuntimeMoniker.CoreRt60)]
[MemoryDiagnoser]
public class InitialisingEmptyArray
{
    // |    Runtime |     Mean |     Error |    StdDev | Ratio |  Gen 0 | Allocated |
    // | CoreRT 5.0 | 4.197 ns | 0.0308 ns | 0.0240 ns |  1.00 | 0.0077 |      24 B |
    // | CoreRT 6.0 | 3.056 ns | 0.0213 ns | 0.0177 ns |  1.00 | 0.0077 |      24 B |
    [Benchmark(Baseline = true)]
    public int[] EmptyArrayByNewT()
    {
        return new int[0];
    }

    // |    Runtime |     Mean |     Error |    StdDev | Ratio |  Gen 0 | Allocated |
    // | CoreRT 5.0 | 1.818 ns | 0.0170 ns | 0.0159 ns |  0.43 |      - |         - |
    // | CoreRT 6.0 | 1.784 ns | 0.0190 ns | 0.0178 ns |  0.58 |      - |         - |
    [Benchmark]
    public int[] EmptyArrayByArrayEmpty()
    {
        return Array.Empty<int>();
    }
}

From the results, Array.Empty<T>() is a scalable solution as there is no memory allocation for each instance, whereas there is 24B of memory being allocated for each new T[0] instance. This also matches with Microsoft's Code Analysis rule CA1825. This is because Array.Empty is a statically allocated empty array instance, and therefore the memory allocation is shared across all invocations of this method.

P.S. Please take the timings with a pinch of salt as this is being run on my local PC and your results may differ. The important thing is the Ratio and Memory Allocation.

You can find the source code behind this on my GitHub: github.com/mithileshz/Benchmarker

Setup

BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19044.1645 (21H2)
Intel Core i5-4460 CPU 3.20GHz (Haswell), 1 CPU, 4 logical and 4 physical cores
.NET SDK=6.0.300-preview.22204.3
  [Host]     : .NET 5.0.15 (5.0.1522.11506), X64 RyuJIT
  CoreRT 5.0 : .NET 6.0.0-rc.1.21420.1, X64 AOT
  CoreRT 6.0 : .NET 6.0.0-rc.1.21420.1, X64 AOT

Did you find this article valuable?

Support Mithilesh Zavar by becoming a sponsor. Any amount is appreciated!