Skip to content

Arg<T>.Latest allocates a full snapshot for long capture histories #7830

Closed

Description

@thomhurst

Summary

Reading Arg<T>.Latest after many matching mock calls copies the entire capture history into a new array to return one value. Repeated reads therefore allocate in proportion to the number of previous calls, even when the caller never requests Values. Reading the latest captured value should avoid this history-sized allocation.

Reproduction

Configure an integer argument matcher and record 30,000 calls:

using TUnit.Mocks;
using TUnit.Mocks.Arguments;

public interface IConsumer
{
    int Consume(int value);
}

// Inside a test method:
var input = Arg.Any<int>();
var mock = IConsumer.Mock();
mock.Consume(input).Returns(1);
for (var i = 0; i < 30_000; i++)
{
    mock.Object.Consume(i);
}

_ = input.Latest; // Warm the read path.
var before = GC.GetAllocatedBytesForCurrentThread();
var latest = input.Latest;
var allocated = GC.GetAllocatedBytesForCurrentThread() - before;
GC.KeepAlive(latest); // Keep boxing outside the measured region.
Console.WriteLine(allocated);

The warmed probe reports 120,096 B per read on .NET 11.0.0. The same result occurs on .NET 10.0.15. CapturingMatcher.Latest at 3353473565 calls ConcurrentQueue<T>.ToArray() before selecting the last element.

Expected and actual

Expected: retrieving the most recently captured value does not copy the full history. Actual: each read allocates and copies the history. Preserve ordering and consistent reads under concurrent capture, including value types larger than a machine word. Benchmark ordinary capture as well as Latest reads so improving reads does not silently slow every mock call.

This is separate from #7822's first-call capture allocation work: compact initial storage can improve fresh mocks while leaving reads from a long queue unchanged.

Environment

Windows 11 x64; .NET SDK 11.0.100; .NET 11.0.0 and 10.0.15; Release; source revision 3353473.

Please remove the history-sized Latest allocation while preserving capture semantics and throughput.

Activity

  1. added
    enhancement
    performance
    P3
    on Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3enhancementperformance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions