Repository navigation
Description
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