Performance Optimization Report
Guiding idea: the fastest program is the one that does the least work on the most
cache-friendly data — everything else is detail. Your job is to find where the
program does too much work or touches memory badly, and write a clear report on how
to fix it and what speedup to expect. Report first; don't rewrite hot code until
the user approves — performance changes can alter behavior and hurt readability.
Step 0 — Measure, don't guess (most important rule)
Optimization without measurement is superstition. The bottleneck is rarely where
intuition says. Per Amdahl's Law, optimizing code that's 1% of runtime yields at
most 1% — effort must go to the actual hot path.
- Look for existing benchmarks/profiles. If none, recommend how to profile this
stack (e.g.
cProfile/py-spy for Python, perf/flamegraph for native,
Chrome DevTools/--prof for JS, pprof for Go, JMH for Java) and what workload to
measure under.
- Be explicit about confidence: mark each finding as measured (backed by a
profile/benchmark) vs suspected (inferred from reading the code). Never present
a guess as a proven hotspot.
Step 1 — Understand the codebase
- Map the architecture, entry points, and the hot paths users actually wait on
(request handlers, render loops, batch jobs, tight inner loops).
- Identify the language/runtime — it changes what matters (GC pressure in
managed langs, cache layout in native, event-loop blocking in JS, the GIL in
Python, allocations everywhere).
- Note the data: sizes, shapes, access patterns, and where data crosses boundaries
(DB, network, disk, serialization).
Step 2 — Analyze against the five principles
For each, find concrete issues and cite file:line.
1. Do less work — algorithmic complexity (biggest wins)
- Better algorithms/data structures beat micro-tweaks. O(n²)→O(n log n) dwarfs any
constant-factor gain. Look for: nested loops over the same data, linear scans that
should be hash/index lookups, repeated sorting, quadratic string building.
- Eliminate redundant computation: hoist invariants out of loops, memoize/cache
pure results, avoid recomputing what hasn't changed.
- Watch for hidden O(n) per call (e.g.
list.contains in a loop) and N+1 queries.
2. Respect the memory hierarchy — data locality
- CPUs are starved by memory, not compute; a cache miss costs ~100× an arithmetic op.
- Prefer contiguous data (arrays over linked lists / pointer-chasing object
graphs), sequential access (prefetcher-friendly), and packing hot fields tightly
so the working set fits in cache. Flag structure-of-arrays vs array-of-structures
opportunities for hot loops (data-oriented design).
3. Reduce overhead
- Cut allocations and GC pressure (reuse buffers, pool objects, avoid boxing).
- Batch I/O and system calls (one bulk DB query/write, not per-row); buffer.
- Don't pay for abstractions you don't need in hot loops (excess indirection, virtual
dispatch, deep call chains, needless copies).
4. Exploit parallelism
- Use cores (threads/async), overlap I/O with compute instead of blocking,
parallelize independent work. Note SIMD/vectorization chances in numeric loops.
- Reduce dependency chains and unpredictable branches that stall the pipeline.
- Be honest about cost: concurrency adds bugs/locks — recommend only where the win is
real and the work is actually independent.
5. Right-size everything else
- Connection pooling, lazy vs eager loading, compression trade-offs, caching layers,
appropriate data types and indexes.
Step 3 — Write the report
Rank findings by impact, not by how easy they are to spot. For each:
- Location —
file:line and the hot path it's on.
- Principle — which of the five.
- Problem — what work/memory cost is being paid, with complexity (e.g. "O(n²)
over
users, n≈10k").
- Fix — concrete change, with a corrected snippet where useful.
- Expected effect — speed/memory impact, framed honestly: a rough magnitude
("~n× fewer comparisons", "removes ~1 DB round-trip per row") and a note that
Amdahl's Law caps the gain by this path's share of total runtime — so tie it to
how hot the path actually is.
- Effort & risk — small/medium/large; does it change behavior or readability?
- Confidence — measured vs suspected.
Suggested layout:
# Optimization Report — <scope> — <date>
## How this was assessed
<profiled? or read-only inference? what workload>
## Top opportunities (ranked by impact)
### 1. [HIGH] N+1 queries in order listing — Principle 1 (do less work)
- Location: src/api/orders.js:48 (per-request hot path)
- Problem: 1 query + N per-row queries; O(n) round-trips, n = #orders.
- Fix: single JOIN / batched `WHERE id IN (...)`.
- Expected effect: ~N fewer DB round-trips; if this path is ~60% of request time,
expect a large latency drop. Confirm with a before/after benchmark.
- Effort: small · Risk: low · Confidence: suspected (profile to confirm)
## Lower-priority / micro-optimizations
## Not worth it / premature
<things that look slow but are cold paths — Amdahl says skip>
End with: "Want me to implement any of these? Tell me which and I'll apply it and
re-measure."
Rules
- Measure before claiming. Distinguish measured hotspots from suspected ones;
recommend profiling when there's no data. Don't dress up guesses as facts.
- Impact-ranked, Amdahl-aware. Push algorithmic/hot-path wins first; call out
premature/cold-path optimizations as not worth it.
- Report, don't rewrite hot code until approved. Note when a speedup costs
readability or changes behavior — that's a trade-off the user should choose.
- Correctness first. A faster wrong answer is worthless; preserve behavior and
recommend re-running tests/benchmarks after any change.
1---2name: optimize3description: Analyze a codebase for performance and produce an optimization report — where the program is slow, how to make it faster, and the expected speed impact, effort, and risk of each change. Use when the user asks to "optimize the program", "make it faster", "improve performance", "find bottlenecks", "why is this slow", or "reduce latency/memory". Reads and understands the code first, reasons from profiling and algorithmic complexity (not guesses), and reports recommendations ranked by impact — without rewriting hot code until asked.4---56# Performance Optimization Report78Guiding idea: **the fastest program is the one that does the least work on the most9cache-friendly data — everything else is detail.** Your job is to find where the10program does too much work or touches memory badly, and write a clear report on how11to fix it and what speedup to expect. **Report first; don't rewrite hot code until12the user approves** — performance changes can alter behavior and hurt readability.1314## Step 0 — Measure, don't guess (most important rule)1516Optimization without measurement is superstition. The bottleneck is rarely where17intuition says. Per **Amdahl's Law**, optimizing code that's 1% of runtime yields at18most 1% — effort must go to the actual hot path.1920- Look for existing benchmarks/profiles. If none, **recommend how to profile this21 stack** (e.g. `cProfile`/`py-spy` for Python, `perf`/`flamegraph` for native,22 Chrome DevTools/`--prof` for JS, `pprof` for Go, JMH for Java) and what workload to23 measure under.24- Be explicit about confidence: mark each finding as **measured** (backed by a25 profile/benchmark) vs **suspected** (inferred from reading the code). Never present26 a guess as a proven hotspot.2728## Step 1 — Understand the codebase2930- Map the architecture, entry points, and the hot paths users actually wait on31 (request handlers, render loops, batch jobs, tight inner loops).32- Identify the language/runtime — it changes what matters (GC pressure in33 managed langs, cache layout in native, event-loop blocking in JS, the GIL in34 Python, allocations everywhere).35- Note the data: sizes, shapes, access patterns, and where data crosses boundaries36 (DB, network, disk, serialization).3738## Step 2 — Analyze against the five principles3940For each, find concrete issues and cite `file:line`.4142### 1. Do less work — algorithmic complexity (biggest wins)43- Better algorithms/data structures beat micro-tweaks. O(n²)→O(n log n) dwarfs any44 constant-factor gain. Look for: nested loops over the same data, linear scans that45 should be hash/index lookups, repeated sorting, quadratic string building.46- Eliminate redundant computation: hoist invariants out of loops, **memoize/cache**47 pure results, avoid recomputing what hasn't changed.48- Watch for hidden O(n) per call (e.g. `list.contains` in a loop) and **N+1 queries**.4950### 2. Respect the memory hierarchy — data locality51- CPUs are starved by memory, not compute; a cache miss costs ~100× an arithmetic op.52- Prefer **contiguous data** (arrays over linked lists / pointer-chasing object53 graphs), **sequential access** (prefetcher-friendly), and packing hot fields tightly54 so the working set fits in cache. Flag structure-of-arrays vs array-of-structures55 opportunities for hot loops (data-oriented design).5657### 3. Reduce overhead58- Cut allocations and **GC pressure** (reuse buffers, pool objects, avoid boxing).59- **Batch** I/O and system calls (one bulk DB query/write, not per-row); buffer.60- Don't pay for abstractions you don't need in hot loops (excess indirection, virtual61 dispatch, deep call chains, needless copies).6263### 4. Exploit parallelism64- Use cores (threads/async), **overlap I/O with compute** instead of blocking,65 parallelize independent work. Note SIMD/vectorization chances in numeric loops.66- Reduce dependency chains and unpredictable branches that stall the pipeline.67- Be honest about cost: concurrency adds bugs/locks — recommend only where the win is68 real and the work is actually independent.6970### 5. Right-size everything else71- Connection pooling, lazy vs eager loading, compression trade-offs, caching layers,72 appropriate data types and indexes.7374## Step 3 — Write the report7576Rank findings by **impact**, not by how easy they are to spot. For each:7778- **Location** — `file:line` and the hot path it's on.79- **Principle** — which of the five.80- **Problem** — what work/memory cost is being paid, with complexity (e.g. "O(n²)81 over `users`, n≈10k").82- **Fix** — concrete change, with a corrected snippet where useful.83- **Expected effect** — speed/memory impact, framed honestly: a rough magnitude84 ("~n× fewer comparisons", "removes ~1 DB round-trip per row") and a note that85 **Amdahl's Law caps the gain by this path's share of total runtime** — so tie it to86 how hot the path actually is.87- **Effort & risk** — small/medium/large; does it change behavior or readability?88- **Confidence** — measured vs suspected.8990Suggested layout:9192```93# Optimization Report — <scope> — <date>9495## How this was assessed96<profiled? or read-only inference? what workload>9798## Top opportunities (ranked by impact)99### 1. [HIGH] N+1 queries in order listing — Principle 1 (do less work)100- Location: src/api/orders.js:48 (per-request hot path)101- Problem: 1 query + N per-row queries; O(n) round-trips, n = #orders.102- Fix: single JOIN / batched `WHERE id IN (...)`.103- Expected effect: ~N fewer DB round-trips; if this path is ~60% of request time,104 expect a large latency drop. Confirm with a before/after benchmark.105- Effort: small · Risk: low · Confidence: suspected (profile to confirm)106107## Lower-priority / micro-optimizations108## Not worth it / premature109<things that look slow but are cold paths — Amdahl says skip>110```111112End with: *"Want me to implement any of these? Tell me which and I'll apply it and113re-measure."*114115## Rules116117- **Measure before claiming.** Distinguish measured hotspots from suspected ones;118 recommend profiling when there's no data. Don't dress up guesses as facts.119- **Impact-ranked, Amdahl-aware.** Push algorithmic/hot-path wins first; call out120 premature/cold-path optimizations as not worth it.121- **Report, don't rewrite** hot code until approved. Note when a speedup costs122 readability or changes behavior — that's a trade-off the user should choose.123- **Correctness first.** A faster wrong answer is worthless; preserve behavior and124 recommend re-running tests/benchmarks after any change.