3

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?

rerez
  • 111
  • 5
  • 3
    `Person` is a class or a struct? Also [docs](https://benchmarkdotnet.org/articles/configs/diagnosers.html#restrictions) state that _"MemoryDiagnoser is `99.5%` accurate about allocated memory when using default settings or Job.ShortRun"_ so maybe this is an example of `0.5%`? =) – Guru Stron Jun 30 '21 at 11:50
  • @GuruStron Person is a simple class. I've tried with all types of runs of 'MemoryDiagnoser' each ends up with the same memory allocated. A similar result in other methods i tested, I need to know why the memory allocation and according to what the size estimate is done – rerez Jun 30 '21 at 11:56
  • Also I was not able to reproduce on my machine. can you please add definition for `Person`? – Guru Stron Jun 30 '21 at 11:58
  • 1
    Also maybe [this](https://adamsitnik.com/the-new-Memory-Diagnoser/) can shed some light on the issue. – Guru Stron Jun 30 '21 at 12:01

0 Answers0