Search code examples
c#.netbenchmarkingallocation

Array.Empty<int>(): Why does Rider show an allocation occurred, but BenchmarkDotNet doesn't?


The memory tool being used in the first image is from Rider. As far as I'm aware, it shows allocations to the managed heap. The second image shows the results from BenchmarkDotNet.

Why does Rider show that an allocation was made, but BenchmarkDotNet indicates that no allocations to the heap were made?

If I instead use the below code sample, BenchmarkDotNet picks up the allocation:

var i = new int[0];

Rider memory tool results

BenchmarkDotNet results


Solution

  • Array.Empty points to an array that the framework has already statically allocated (see here).

    When you call new int[0], a new array with size 0 is actually allocated just for you.

    See also this answer.