⚡ perf: remove linq allocations in header filtering#13
Conversation
Replaced `.Where().Select().ToArray()` LINQ calls in `IdempotencyService` with a manual loop helper method `FilterHeaderValues`. This avoids unnecessary memory allocations (closures, delegate allocations, enumerator boxing, array resizing) on every request that uses idempotency headers. Benchmark results show execution time reduced from ~163ns to ~60ns and allocations reduced from 200B to 56B. Co-authored-by: movsal08 <33213388+movsal08@users.noreply.github.com>
|
👋 Jules, reporting for duty! I'm here to lend a hand with this pull request. When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down. I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job! For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
💡 What: The optimization implemented
Replaced the LINQ expression
.Where(x => x != null).Select(x => x!).ToArray()with a manual helper functionFilterHeaderValuesthat iterates over theStringValuesto correctly size the array and populate it without using LINQ enumerators. This was applied to both the request header parsing and the response header snapshotting logic inIdempotencyService.cs.🎯 Why: The performance problem it solves
Using LINQ
.Where().Select().ToArray()on the hot path for every request creates multiple temporary allocations (a closure, multiple delegate instances, boxing an enumerator, and internally resizing a list to build the array). Removing it avoids 144 bytes of allocations per header array created, easing GC pressure under high request load.📊 Measured Improvement:
Before (LINQ): 163.92 ns, 200 B allocated.
After (Manual Loop): 60.26 ns, 56 B allocated.
The change results in ~63% less CPU time and ~72% fewer memory allocations for this specific operation.