# Performance Optimization

> Identify and resolve performance bottlenecks systematically.

## When to Use
- "This is slow" / "optimize this"
- Load testing reveals bottlenecks
- Database queries taking too long

## Approach — MEASURE FIRST
1. **Profile before optimizing** — measure, don't guess
2. **Find the bottleneck** — is it CPU, memory, I/O, network, or database?
3. **Optimize the bottleneck** — improving non-bottleneck code is waste
4. **Measure after** — quantify the improvement
5. **Repeat** — the new bottleneck is now somewhere else

## Common Bottleneck Fixes
- **N+1 queries** — batch fetch, eager loading, join instead of loop
- **Missing indexes** — EXPLAIN the query, add indexes on WHERE/JOIN columns
- **Unnecessary computation** — cache results, memoize, precompute
- **Large payloads** — paginate, compress, return only needed fields
- **Synchronous I/O** — async/await, connection pooling, parallel requests
- **Memory leaks** — profile memory usage, check for growing collections

## Golden Rule
Never optimize without a benchmark. "I think it's faster" is not measurement. Before and after numbers or it didn't happen.
