3

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

1 Answers1

5

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.

Tomer
  • 1,606
  • 12
  • 18
  • Thanks for the links. I guess I'm bit confused since Rider shows the first 4 int arrays already initialized (as in the above image) before the first line of code is ran. Only after the call to Array.Empty does Rider's memory tool pick up the "default" int[0]. Rider even shows the total bytes allocated for System.Int32[] increase from 3600 to 3624 after the call. – user3476332 May 02 '22 at 15:39
  • Statically allocated means here it happens on the first usage of the Array class. So maybe BenchmarkDotNet needed an array for its benchmarking framework before and the static array has been created already but in a simple app as first thing in a main method it has not. So two different contexts two different behaviors. – Ralf May 02 '22 at 16:15
  • @Ralf I can't see another possibility when you put it like that. Thanks for your explanation. – user3476332 May 02 '22 at 16:33
  • @Ralf _"Statically allocated means here it happens on the first usage of the Array class"_ - take note: Gravell, Marc, _["Oh, that is complex. It depends on whether the beforefieldinit flag is set, which in turn (in C#) depends on whether there is a static constructor. And worse; in .NET 4 I believe the behaviour changed to make it more "lazy" than it used to be"](https://stackoverflow.com/a/3966055/585968)_ –  May 05 '22 at 05:36
  • Tomer, whilst your second link is useful, it doesn't really focus on the static behaviour you mentioned. You might like [this answer](https://stackoverflow.com/a/3966055/585968) by Mr Gravell which does describe static behaviour. The post then branches out to further posts by Mr Skeet. –  May 05 '22 at 05:44