# Performance Rule

> **Applied when writing code that may impact performance.**

---

## When Applied

- Database queries
- API endpoints
- Data processing
- Frontend rendering
- File operations

---

## Database Performance

### Avoid N+1 Queries
```python
# ❌ N+1 Problem
users = User.query.all()
for user in users:
    print(user.posts)  # Separate query for each user

# ✅ Eager loading
users = User.query.options(joinedload(User.posts)).all()
for user in users:
    print(user.posts)  # Already loaded
```

### Use Indexes
```python
# Ensure indexes on frequently queried columns
class User(Base):
    email = Column(String, index=True)  # Indexed
    created_at = Column(DateTime, index=True)
```

### Pagination Required
```python
# ❌ Loading all records
users = User.query.all()

# ✅ Paginated
users = User.query.offset(page * size).limit(size).all()
```

---

## API Performance

### Batch Operations
```python
# ❌ Multiple round trips
for item in items:
    await save_item(item)

# ✅ Batch insert
await save_items(items)
```

### Caching
```python
# Cache expensive operations
@cache(ttl=300)
def get_aggregated_stats():
    return compute_expensive_stats()
```

### Response Size
```python
# ❌ Return everything
return user.to_dict()  # Includes all fields

# ✅ Return only needed fields
return {
    "id": user.id,
    "name": user.name
}
```

---

## Frontend Performance

### React Rendering
```typescript
// ❌ Unnecessary re-renders
const Component = () => {
  const items = data.filter(x => x.active);  // Recalculated every render
  ...
};

// ✅ Memoized
const Component = () => {
  const items = useMemo(
    () => data.filter(x => x.active),
    [data]
  );
  ...
};
```

### List Rendering
```typescript
// ✅ Virtualize long lists
import { FixedSizeList } from 'react-window';

<FixedSizeList
  height={400}
  itemCount={items.length}
  itemSize={50}
>
  {({ index, style }) => <Item style={style} item={items[index]} />}
</FixedSizeList>
```

### Bundle Size
```typescript
// ✅ Code splitting
const Dashboard = lazy(() => import('./pages/Dashboard'));
```

---

## Data Processing

### Memory Efficiency
```python
# ❌ Load entire file into memory
data = file.read()

# ✅ Process in chunks
for chunk in iter(lambda: file.read(8192), b''):
    process(chunk)
```

### Generator Usage
```python
# ❌ Build entire list
def get_items():
    return [process(x) for x in large_dataset]

# ✅ Generator (lazy evaluation)
def get_items():
    for x in large_dataset:
        yield process(x)
```

---

## Async Operations

### Don't Block Event Loop
```python
# ❌ Blocking in async context
async def handler():
    result = blocking_operation()  # Blocks!

# ✅ Run in executor
async def handler():
    result = await asyncio.to_thread(blocking_operation)
```

### Concurrent Operations
```python
# ✅ Parallel execution
results = await asyncio.gather(
    fetch_users(),
    fetch_posts(),
    fetch_comments()
)
```

---

## Enforcement

Performance issues flagged:
1. Code reviewer detects patterns
2. Profiling in development
3. Monitoring in production
