Skip to content

perf: Reduce per-request allocations, eliminate regex recompilation, and modernize to async I/O#131

Merged
hibri merged 6 commits intomasterfrom
copilot/improve-httpmock-performance
Apr 25, 2026
Merged

perf: Reduce per-request allocations, eliminate regex recompilation, and modernize to async I/O#131
hibri merged 6 commits intomasterfrom
copilot/improve-httpmock-performance

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Apr 22, 2026

Systematic performance audit and fixes across the HttpMock request pipeline, targeting allocations and CPU work on every request.

Critical — per-request regex and I/O

  • Regex caching: EndpointMatchingRule.MatchPath was constructing a new Regex for every handler×request match attempt. Now cached in a static ConcurrentDictionary<string, Regex> with RegexOptions.Compiled.
  • FileResponseBody: Range regex made static readonly; single Match() replaces IsMatch() + Match(). File reads now seek to offset instead of allocating the entire file into memory.
  • Async I/O: IRequestProcessor.OnRequest returns Task; body reading uses ReadToEndAsync. HttpServer listener loop uses GetContextAsync(), removing the dedicated Thread.

High — hot-path allocation reduction

  • HeaderMatch: TryGetValue O(1) lookup with case-insensitive fallback replaces O(H×R) .Any() scan.
  • RequestMatcher: Single foreach with early exit replaces three chained .Where() + FirstOrDefault().
  • EndpointMatchingRule: Short-circuits on method mismatch before parsing query string or headers.
  • _handlers.Count() (LINQ, O(n)) → .Count (O(1))
  • header.Key.ToLowerInvariant()string.Equals(..., OrdinalIgnoreCase)
  • new byte[0]Array.Empty<byte>()
  • Debug log calls guarded with IsEnabled(LogLevel.Debug) to avoid SanitizeForLog allocations
  • Pre-sized Dictionary in HandleContext using header count

Threading

  • HttpServerFactory: Double-check lock pattern — BuildServer() (which calls Start() + TCP polling) now runs outside _serverLock.
  • Fire-and-forget HandleContextAsync gets .ContinueWith(OnlyOnFaulted) error handler.

Breaking change

IRequestProcessor.OnRequest signature changed from void to Task. Unit tests updated to async Task accordingly.

@hibri
Copy link
Copy Markdown
Owner

hibri commented Apr 22, 2026

@copilot resolve the merge conflicts in this pull request

@hibri hibri marked this pull request as ready for review April 23, 2026 11:18
@hibri hibri merged commit 2f7c825 into master Apr 25, 2026
1 check passed
@hibri hibri deleted the copilot/improve-httpmock-performance branch April 25, 2026 19:25
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.

2 participants