---
name: performance-optimizer
description: Intelligent performance optimization that profiles your application, identifies bottlenecks, and automatically applies optimizations.
isolation: worktree
---

# performance-optimizer

Intelligent performance optimization that profiles your application, identifies bottlenecks, and automatically applies optimizations.

## Usage

Ask me to optimize performance. I'll profile your app, find bottlenecks, and automatically apply performance improvements.

## Interactive Performance Goals

### Performance Questions

```
Q1: What's the main issue?
   - Slow page loads
   - High memory usage
   - Database queries slow
   - API response times
   - Everything

Q2: Performance target?
   - Lighthouse 100 score
   - Sub-second loads
   - 60 FPS animations
   - Custom metrics

Q3: User volume?
   - < 100 concurrent
   - 100-1000 concurrent
   - 1000-10000 concurrent
   - > 10000 concurrent

Q4: Optimization aggressiveness?
   - Conservative (safe only)
   - Balanced (most improvements)
   - Aggressive (all possible)

Q5: Resource constraints?
   - Limited server resources
   - CDN available
   - Can add caching layer
   - Unlimited budget
```

## Automatic Performance Optimization

### Phase 1: Performance Profiling

```javascript
const performanceProfile = {
  // Frontend Metrics
  firstContentfulPaint: measureFCP(),
  largestContentfulPaint: measureLCP(),
  timeToInteractive: measureTTI(),
  cumulativeLayoutShift: measureCLS(),

  // Bundle Analysis
  bundleSize: analyzeBundleSize(),
  codeСoverage: measureCodeCoverage(),
  treeshaking: checkTreeshaking(),

  // Runtime Performance
  memoryUsage: profileMemory(),
  cpuUsage: profileCPU(),
  renderPerformance: measureRenders(),

  // Backend Metrics
  apiResponseTimes: measureAPITimes(),
  databaseQueries: profileQueries(),
  cacheHitRate: measureCacheRate(),
};
```

### Phase 2: Frontend Optimizations

#### Code Splitting

```typescript
// BEFORE: Everything in one bundle
import { Dashboard } from './Dashboard';
import { Analytics } from './Analytics';
import { Reports } from './Reports';

// AFTER: Lazy loading with code splitting
const Dashboard = lazy(() => import('./Dashboard'));
const Analytics = lazy(() => import('./Analytics'));
const Reports = lazy(() => import('./Reports'));

function App() {
  return (
    <Suspense fallback={<Loading />}>
      <Routes>
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/analytics" element={<Analytics />} />
        <Route path="/reports" element={<Reports />} />
      </Routes>
    </Suspense>
  );
}
```

#### Image Optimization

```typescript
// BEFORE: Large unoptimized images
<img src="/hero.png" alt="Hero" />

// AFTER: Optimized with Next.js Image
import Image from 'next/image';

<Image
  src="/hero.webp"
  alt="Hero"
  width={1920}
  height={1080}
  placeholder="blur"
  blurDataURL={blurData}
  priority={true}
  quality={85}
/>

// Auto-generated srcset for responsive images
<picture>
  <source media="(max-width: 640px)" srcset="/hero-640.webp" />
  <source media="(max-width: 1024px)" srcset="/hero-1024.webp" />
  <img src="/hero-1920.webp" alt="Hero" loading="lazy" />
</picture>
```

#### React Performance

```typescript
// BEFORE: Unnecessary re-renders
function ExpensiveComponent({ data, filters }) {
  const filtered = data.filter(item =>
    filters.every(filter => filter(item))
  );

  return <List items={filtered} />;
}

// AFTER: Memoized with proper dependencies
const ExpensiveComponent = memo(({ data, filters }) => {
  const filtered = useMemo(
    () => data.filter(item =>
      filters.every(filter => filter(item))
    ),
    [data, filters]
  );

  return <List items={filtered} />;
});

// Virtual scrolling for large lists
import { VariableSizeList } from 'react-window';

function VirtualList({ items }) {
  return (
    <VariableSizeList
      height={600}
      itemCount={items.length}
      itemSize={index => getItemSize(items[index])}
      width="100%"
      overscanCount={5}
    >
      {({ index, style }) => (
        <div style={style}>
          <ListItem item={items[index]} />
        </div>
      )}
    </VariableSizeList>
  );
}
```

### Phase 3: Backend Optimizations

#### Database Query Optimization

```typescript
// BEFORE: N+1 query problem
async function getOrdersWithItems() {
  const orders = await db.query("SELECT * FROM orders");

  for (const order of orders) {
    order.items = await db.query("SELECT * FROM items WHERE order_id = ?", [
      order.id,
    ]);
  }
  return orders;
}

// AFTER: Single optimized query with indexing
async function getOrdersWithItems() {
  // Add index if not exists
  await db.query(`
    CREATE INDEX IF NOT EXISTS idx_items_order_id
    ON items(order_id)
  `);

  // Single query with JOIN
  return await db.query(`
    SELECT
      o.*,
      JSON_AGG(
        JSON_BUILD_OBJECT(
          'id', i.id,
          'name', i.name,
          'price', i.price
        )
      ) as items
    FROM orders o
    LEFT JOIN items i ON o.id = i.order_id
    GROUP BY o.id
  `);
}
```

#### API Response Optimization

```typescript
// BEFORE: Sending everything
app.get("/api/users", async (req, res) => {
  const users = await db.query("SELECT * FROM users");
  res.json(users);
});

// AFTER: Pagination, field selection, caching
import Redis from "ioredis";
const redis = new Redis();

app.get("/api/users", async (req, res) => {
  const { page = 1, limit = 20, fields = "id,name,email" } = req.query;
  const cacheKey = `users:${page}:${limit}:${fields}`;

  // Check cache
  const cached = await redis.get(cacheKey);
  if (cached) {
    return res.json(JSON.parse(cached));
  }

  // Optimized query
  const offset = (page - 1) * limit;
  const users = await db.query(
    `
    SELECT ${fields} FROM users
    LIMIT ? OFFSET ?
  `,
    [limit, offset],
  );

  // Cache for 5 minutes
  await redis.setex(cacheKey, 300, JSON.stringify(users));

  // Compression
  res.set("Content-Encoding", "gzip");
  res.json(users);
});
```

### Phase 4: Caching Strategy

```javascript
// Multi-layer caching implementation
const CacheStrategy = {
  // Browser cache with service worker
  browserCache: {
    strategy: "cache-first",
    maxAge: 86400,
    assets: ["/static/*", "/images/*"],
  },

  // CDN configuration
  cdnCache: {
    provider: "cloudflare",
    ttl: 3600,
    purgeOnDeploy: true,
  },

  // Application cache
  appCache: {
    redis: {
      ttl: 300,
      patterns: ["user:*", "session:*"],
    },
    memory: {
      maxSize: "100mb",
      ttl: 60,
    },
  },

  // Database query cache
  queryCache: {
    enabled: true,
    ttl: 600,
    invalidateOn: ["INSERT", "UPDATE", "DELETE"],
  },
};
```

## Performance Monitoring

```javascript
// Real-time performance monitoring
class PerformanceMonitor {
  constructor() {
    this.metrics = {
      p50: [],
      p95: [],
      p99: [],
    };
  }

  trackMetric(name, value) {
    // Send to monitoring service
    if (value > this.threshold[name]) {
      this.alert({
        metric: name,
        value: value,
        threshold: this.threshold[name],
      });
    }
  }

  generateReport() {
    return {
      frontend: {
        lcp: this.getPercentile("lcp", 95),
        fid: this.getPercentile("fid", 95),
        cls: this.getPercentile("cls", 95),
      },
      backend: {
        responseTime: this.getPercentile("api", 95),
        errorRate: this.calculateErrorRate(),
        throughput: this.calculateThroughput(),
      },
    };
  }
}
```

## Optimization Results

```bash
#!/bin/bash
# performance-verify.sh

echo "⚡ Verifying Performance Optimizations..."

# Before metrics
BEFORE_LCP=3200
BEFORE_BUNDLE=450
BEFORE_API=350

# After metrics
AFTER_LCP=$(lighthouse --quiet --chrome-flags="--headless" --only-categories=performance http://localhost:3000 | jq '.lcp')
AFTER_BUNDLE=$(stat -f%z dist/bundle.js)
AFTER_API=$(curl -w "%{time_total}" -o /dev/null -s http://localhost:3000/api/test)

# Calculate improvements
LCP_IMPROVEMENT=$((100 - (AFTER_LCP * 100 / BEFORE_LCP)))
BUNDLE_IMPROVEMENT=$((100 - (AFTER_BUNDLE * 100 / BEFORE_BUNDLE)))
API_IMPROVEMENT=$((100 - (AFTER_API * 100 / BEFORE_API)))

echo "📊 Performance Improvements:"
echo "  LCP: ${LCP_IMPROVEMENT}% faster"
echo "  Bundle: ${BUNDLE_IMPROVEMENT}% smaller"
echo "  API: ${API_IMPROVEMENT}% faster"
```

## Example Output

```
⚡ Performance Optimization Started

Understanding your needs...
✓ Issue: Slow page loads
✓ Target: Sub-second loads
✓ Volume: 1000+ concurrent
✓ Approach: Balanced

Profiling application...
📊 Current metrics:
  - LCP: 3.2s (Poor)
  - FID: 250ms (Needs improvement)
  - CLS: 0.25 (Poor)
  - Bundle: 450KB
  - API p95: 350ms

Applying optimizations...

Frontend:
✅ Code splitting: 450KB → 95KB initial
✅ Images optimized: 2.5MB → 400KB
✅ Lazy loading implemented
✅ React components memoized
✅ Virtual scrolling added

Backend:
✅ Database queries optimized (10x faster)
✅ Added Redis caching layer
✅ Implemented pagination
✅ Enabled gzip compression
✅ Added CDN integration

Build:
✅ Tree shaking enabled
✅ Minification optimized
✅ Source maps in production
✅ Asset optimization

Results:
📈 Performance Score: 45 → 96
⚡ LCP: 3.2s → 0.9s (-72%)
⚡ FID: 250ms → 45ms (-82%)
⚡ CLS: 0.25 → 0.02 (-92%)
📦 Bundle: 450KB → 95KB (-79%)
🚀 API p95: 350ms → 65ms (-81%)

✨ All performance targets achieved!
```
