Check Memory Traffic
warning
To be able to analyze memory traffic, you must turn on the collecting of memory allocation data. The AssertTraffic attribute does this automatically. In case you use want to analyze traffic between snapshots, you should add the [DotMemoryUnit(CollectAllocations=true)] attribute before the test. Learn more in Collect Allocation Data
When you need just to evaluate the amount of memory allocated in a test, you can use the AssertTraffic attribute.
The attribute is quite flexible and allows you to filter traffic data by objects' type, interface, or namespace.
Note that you can add any number of AssertTraffic
attributes in case you want to filter memory traffic by a number of conditions.
[AssertTraffic(AllocatedSizeInBytes = 1000, Types = new[] { typeof(string) })] // starts collecting traffic data automatically
[Test]
public void TestMethod1()
{
... // Some user code
}
In more complex scenarios (e.g. when you need to check traffic on a specific time interval), you should use the Traffic type.
[DotMemoryUnit(CollectAllocations=true)] // collect traffic data
[Test]
public void TestMethod1()
{
var memoryCheckPoint1 = dotMemory.Check(); // 1
foo.Bar();
var memoryCheckPoint2 = dotMemory.Check(memory =>
{
// 2
Assert.That(memory.GetTrafficFrom(memoryCheckPoint1).Where(obj => obj.Interface.Is<IFoo>()).AllocatedMemory.SizeInBytes,
Is.LessThan(1000));
});
bar.Foo();
dotMemory.Check(memory =>
{
// 3
Assert.That(memory.GetTrafficFrom(memoryCheckPoint2).Where(obj => obj.Type.Is<Bar>()).AllocatedMemory.ObjectsCount,
Is.LessThan(10));
});
}
To mark time intervals where memory traffic can be analyzed, you should use checkpoints created by dotMemory.Check (as you probably guessed, this method simply takes memory snapshot).
The checkpoint that defines the starting point of the interval is passed to the
GetTrafficFrom
method.For example, this line asserts that the total size of objects implementing the
IFoo
interface created on the interval betweenmemoryCheckPoint1
andmemoryCheckPoint2
is less than 1000 bytes.You can use any checkpoint created earlier as a base for analysis. Thus, this line gets traffic data between the current
dotMemory.Check
call andmemoryCheckPoint2
.
dotMemory Unit also provides alternative syntax for traffic queries. You can use the ==
, &
, and |
logic operators to combine a number of queries. For example:
Assert.That(memory.GetTrafficFrom(memoryCheckPoint2).Where(obj => obj.Type == typeof(Foo) | obj.Interface == typeof(IEnumerable))
.AllocatedMemory.ObjectsCount, Is.LessThan(10));