Skip to content

mock: avoid copying call history in AssertNumberOfCalls - #1958

Open
Saauf wants to merge 1 commit into
stretchr:masterfrom
Saauf:perf/mock-assert-number-of-calls
Open

Saauf wants to merge 1 commit into
stretchr:masterfrom
Saauf:perf/mock-assert-number-of-calls

Conversation

@Saauf

@Saauf Saauf commented Sep 5, 2026

Copy link
Copy Markdown

Summary

Avoid copying the entire call history slice in AssertNumberOfCalls by iterating over m.Calls directly.

Changes

  • Iterate over m.Calls directly by index in AssertNumberOfCalls, eliminating slice copy allocations (m.calls()) and per-iteration Call struct copying.
  • Add Benchmark_Mock_AssertNumberOfCalls in mock/mock_test.go to measure and track assertion performance.

Motivation

AssertNumberOfCalls currently calls m.calls(), which copies the entire call history slice into a newly allocated slice before counting entries with a matching method name. AssertNumberOfCalls already acquires m.mutex.Lock() at the start and holds it throughout the counting loop, making slice duplication redundant.

Directly indexing m.Calls under the held mutex significantly improves performance and eliminates slice allocations.

Benchmark comparison (Apple M3, Go 1.25.5, 100 recorded calls, 5 runs):

  • Before: 1923 ns/op, 18,584 B/op, 4 allocs/op
  • After: 508 ns/op, 144 B/op, 3 allocs/op

Result: ~3.8x faster and 99.2% reduction in allocated memory per assertion.

Related issues

Closes #1957

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

mock: avoid copying call history in AssertNumberOfCalls

1 participant