I'm using BenchmarkDotNet
with .netcore 3.1 to benchmark my code.
I encounter a certain issue when I get memory allocation results even though no allocation is made.
Here is an snapshot of what I am doing:
[SimpleJob(RunStrategy.Monitoring, targetCount: 100)]
[MemoryDiagnoser]
public class Temp
{
public static Person[] array1 = Enumerable.Range(0, 100).Select(x => new Person(1, 2)).ToArray();
[Benchmark]
public Person ReturnFirstPerson()
{
return array1[0];
}
}
Person is a simple class:
public class Person
{
public int A;
public int B;
public Person(int a, int b)
{
this.A = a;
this.B = b;
}
}
ReturnFirstPerson
method does not compute or allocate any memory but only returns the first value in the array, these are the benchmark results:
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
|------------------ |---------:|---------:|---------:|------:|------:|------:|----------:|
| ReturnFirstPerson | 266.4 ns | 10.55 ns | 31.10 ns | - | - | - | 48 B |
Can you please explain why the results are showing memory allocation?