demo(16-tolist-in-loop): 16 — LINQ scan inside a per-request loop#165
demo(16-tolist-in-loop): 16 — LINQ scan inside a per-request loop#165
Conversation
See scenarios/16-tolist-in-loop/README.md for the expected verdict.
| foreach (var item in order.Items) | ||
| { | ||
| var matches = order.Items | ||
| .Where(i => i.Sku == item.Sku) |
There was a problem hiding this comment.
GCI0044 — Performance Hotpath Risk
LINQ query inside a loop
Evidence:
Line 13: .Where(i => i.Sku == item.Sku)
💡 Suggested action: Move the LINQ query outside the loop, pre-compute the result into a collection, or use a dictionary/lookup for O(1) access.
Confidence: Medium | Severity: Info
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e4c2ebda8b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| var matches = order.Items | ||
| .Where(i => i.Sku == item.Sku) | ||
| .ToList(); |
There was a problem hiding this comment.
Precompute SKU groups outside the item loop
This method runs order.Items.Where(...).ToList() inside a foreach over order.Items, which means an order with n items triggers n full list scans and n extra allocations (O(n²)). On larger orders, this creates avoidable CPU and GC pressure in the processing path; build the SKU groups once (e.g., GroupBy/dictionary) and reuse them instead of re-filtering on each iteration.
Useful? React with 👍 / 👎.
16 — LINQ scan inside a per-request loop
Expected verdict: ❌ Fails — GauntletCI should fire GCI0044 (performance hot-path risk).
What changed
A new
OrderItemDeduplicatorruns aWherescan inside aforeachover the same list, materialising it with
.ToList()on eachiteration:
For an order with
nitems this is O(n²). For a single-item order itis fine. For the larger orders the analytics team has been asking
about it falls over.
Why this is risky
carries DB and payment latency. Spending O(n²) CPU on a list scan
is exactly the kind of cost that disappears in dev and surfaces
during a launch promo.
GroupBy(or build aDictionary<Sku, List<OrderItem>>) beforethe loop. One pass, O(n).
in this codebase shape; GauntletCI flags it before the n grows.
What GauntletCI catches
GCI0044 Performance Hotpath Risk— a LINQ method (.Where(,.Select(,.FirstOrDefault(,.Any(,.Count() on an added linenested inside a
for/foreach/whileloop in a non-test, non-rulefile.