0

I'm just trying to do something like this using Rider, Xunit and dotMemory Unit (but should be similar with NUnit or Visual Studio):

[DotMemoryUnit(CollectAllocations = true, FailIfRunWithoutSupport = false)]
[Fact]
private void MemoryTest()
{
  int i = 0;
  MemoryCheckPoint memory1 = dotMemory.Check();
  i++; // standin for something much more complicated
  dotMemory.Check(memory => {
      Assert.Equal(0, memory.GetTrafficFrom(memory1).AllocatedMemory.SizeInBytes);
    });
  _testOutputHelper.WriteLine(i.ToString()); // just here to make sure i gets used
}

Obviously I'm using i++ as a standin for something much more complicated that I'd really like to test, but I'd like to get this passing.

What I see is that there's a lot of allocation that happen as the result of taking a checkpoint in dotMemory and those all show up. I think I can exclude the ones that are specific to the JetBrains namespace by using Where with a query, and that helps a bit. However, the bulk of the allocated bytes are in the System namespace in mscorlib and I don't want to exclude those if they're created by my code.

I am trying to test to create allocation-free/garbage-free code, so I really do want to track allocations and assert that my code didn't do any.

I've also gone down the road of trying to noodle on the closure allocation in the dotMemory.Check() call and moving that so it is pre-initialized does not really help much.

My latest version is getting much messier without actually looking like its getting any closer to the answer:

MemoryCheckPoint memory1;
string[] myparams = new[] {"JetBrains"};
Func<TrafficProperty, Query> myquery = obj => obj.Namespace.NotLike(myparams);
Action<Memory> myaction = memory => { Assert.Equal(0, memory.GetTrafficFrom(memory1).Where(myquery).AllocatedMemory.SizeInBytes); };
        
int i = 0;

memory1 = dotMemory.Check();
i++;
dotMemory.Check(myaction);
        
_testOutputHelper.WriteLine(i.ToString());

There's still a bunch of allocations in System which is being done by dotMemory itself.

lamont
  • 3,854
  • 1
  • 20
  • 26
  • To filter out allocations made by dotMemory Unit itself it needs to analyze allocation's stack traces. Unfortunatelly such query is not implemented yet. Sorry. – Ed Pavlov May 31 '21 at 16:03
  • Yeah I managed to write tests using just `GC.GetAllocatedBytesForCurrentThread()` and then use dotMemory unit snapshots to see what is going on. A way too filter based on stack traces would be useful (and considering the fact that i'm trying to drive my own memory allocations to zero the non-failing case should perform fairly well). – lamont Jun 01 '21 at 01:21

0 Answers0