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.