You need to enable JavaScript to run this app. 如何使用dotMemory Unit编写测试校验代码零内存分配?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用dotMemory Unit编写测试校验代码零内存分配?

解决方案

方案1:基于调用栈过滤dotMemory触发的分配

你之前仅过滤了分配对象的JetBrains命名空间,但是dotMemory触发的System命名空间分配,调用栈必然包含JetBrains的底层方法,修改查询规则排除这部分即可完全过滤工具自身的开销:

[DotMemoryUnit(CollectAllocations = true, FailIfRunWithoutSupport = false)]
[Fact]
private void MemoryTest()
{
    // 提前初始化委托和查询规则,避免闭包分配
    MemoryCheckPoint checkpoint;
    var excludeJetBrainsAllocation = (TrafficProperty p) => 
        p.CallStack.All(frame => !frame.Type.Namespace.StartsWith("JetBrains"));
    Action<Memory> checkAction = memory => 
    {
        var businessAllocated = memory.GetTrafficFrom(checkpoint)
            .Where(excludeJetBrainsAllocation)
            .AllocatedMemory.SizeInBytes;
        Assert.Equal(0, businessAllocated);
    };

    // 预热dotMemory接口,消除一次性初始化分配
    dotMemory.Check(_ => {});

    // 正式测试
    int i = 0;
    checkpoint = dotMemory.Check();
    i++; // 替换为实际业务逻辑
    dotMemory.Check(checkAction);

    _testOutputHelper.WriteLine(i.ToString());
}

该规则只会保留调用栈完全不涉及JetBrains代码的分配,也就是你的业务逻辑直接/间接触发的分配,不会漏测也不会误判工具自身的开销

方案2:用运行时原生API做零分配校验

如果只是要验证单线程逻辑无分配,直接使用.NET运行时自带的GC.GetAllocatedBytesForCurrentThread即可,完全没有第三方工具的额外开销,结果更精准:

[Fact]
private void MemoryTest()
{
    // 预热业务逻辑,消除静态构造函数、延迟初始化的一次性分配
    YourBusinessLogic();

    long before = GC.GetAllocatedBytesForCurrentThread();
    
    // 执行待测试逻辑
    int i = 0;
    i++; // 替换为YourBusinessLogic()
    
    long after = GC.GetAllocatedBytesForCurrentThread();

    Assert.Equal(0, after - before);
    _testOutputHelper.WriteLine(i.ToString());
}

如果需要进一步提升精度可以在测试前后加GC.TryStartNoGCRegion/GC.EndNoGCRegion屏蔽运行时的后台GC干扰;如果逻辑涉及多线程分配,需要配合线程同步统计所有相关线程的分配值,或者换回dotMemory方案

方案3:基线差值抵消法

先跑一次无业务逻辑的空测试流程,统计dotMemory自身产生的固定分配量作为基线,实际测试时减去基线值即可消除工具开销:

// 类级别静态变量,仅计算一次基线
private static long _dotMemoryBaseline = -1;

[DotMemoryUnit(CollectAllocations = true, FailIfRunWithoutSupport = false)]
[Fact]
private void MemoryTest()
{
    // 首次运行计算基线
    if (_dotMemoryBaseline < 0)
    {
        var emptyCp = dotMemory.Check();
        // 无业务代码的空流程
        dotMemory.Check(m => 
        {
            _dotMemoryBaseline = m.GetTrafficFrom(emptyCp).AllocatedMemory.SizeInBytes;
        });
    }

    // 正式测试
    int i = 0;
    var cp = dotMemory.Check();
    i++; // 替换为业务逻辑
    dotMemory.Check(m => 
    {
        var totalTraffic = m.GetTrafficFrom(cp).AllocatedMemory.SizeInBytes;
        // 减去基线,剩余为业务逻辑产生的分配
        Assert.Equal(0, totalTraffic - _dotMemoryBaseline);
    });

    _testOutputHelper.WriteLine(i.ToString());
}

内容的提问来源于stack exchange,提问作者lamont

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 04:45:01