dotMemory Unit 3.2 Help

Check Memory Traffic

Check memory traffic

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 }

Filter memory traffic by complex conditions

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)); }); }
  1. 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).

  2. 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 between memoryCheckPoint1 and memoryCheckPoint2 is less than 1000 bytes.

  3. You can use any checkpoint created earlier as a base for analysis. Thus, this line gets traffic data between the current dotMemory.Check call and memoryCheckPoint2.

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));
Last modified: 10 May 2022