Optimize

From MadAppGang/claude-code · View interactive version

Optimize is an AI agent skill from the GitHub repository MadAppGang/claude-code. On-demand performance and optimization analysis. Use when identifying bottlenecks, improving build times, reducing bundle size, or optimizing code performance. Trigger keywords - "optimize", "performance", "bottleneck", "bundle size", "build time", "speed up".

How to use this skill

Skill file

Optimize Skill

Overview

The optimize skill provides comprehensive on-demand performance and optimization analysis for your codebase. It identifies bottlenecks, slow builds, large bundles, inefficient code patterns, and opportunities for performance improvements across all supported technology stacks.

When to Use:

Technology Coverage:

Optimization Categories

1. Build Performance

What Gets Analyzed:

Common Issues:

Optimization Targets:

2. Bundle Size

What Gets Measured:

Bundle Analysis:

Bundle Size Breakdown:
├── vendor.js: 847 KB (312 KB gzipped)
│   ├── react-dom: 142 KB
│   ├── lodash: 71 KB (should use lodash-es)
│   ├── moment: 67 KB (consider date-fns)
│   └── ...
├── main.js: 234 KB (89 KB gzipped)
└── [lazy chunks]: 156 KB total

Optimization Goals:

3. Runtime Performance

What Gets Profiled:

Performance Metrics:

Detection Methods:

4. Memory Usage

What Gets Monitored:

Red Flags:

5. API and Database Performance

What Gets Analyzed:

Database Optimization:

Analysis Patterns

Identifying Bottlenecks

Step 1: Measure Current Performance

Collect baseline metrics:

Step 2: Profile and Identify Hot Paths

Find where time is spent:

Step 3: Prioritize Optimizations

Focus on:

  1. Highest impact (largest bottleneck)
  2. Lowest effort (quick wins)
  3. Most frequent (called often)

Step 4: Measure Impact

After optimization:

Tools and Commands

JavaScript/TypeScript:

# Bundle analysis
npx webpack-bundle-analyzer dist/stats.json

# Build performance
npm run build -- --profile --json > stats.json

# Runtime profiling
node --prof app.js
node --prof-process isolate-*.log > processed.txt

Go:

# Build time analysis
go build -x 2>&1 | ts '[%Y-%m-%d %H:%M:%S]'

# CPU profiling
go test -cpuprofile=cpu.prof -bench=.
go tool pprof cpu.prof

# Memory profiling
go test -memprofile=mem.prof -bench=.
go tool pprof mem.prof

Rust:

# Compile time analysis
cargo build --timings

# Binary size analysis
cargo bloat --release

# Runtime profiling
cargo flamegraph --bench benchmark_name

Optimization Report Format

Performance Report Structure

# Performance Optimization Report

**Generated**: 2026-01-28 14:32:00
**Scope**: Full application analysis
**Baseline**: Established 2026-01-21

## Executive Summary

**Overall Performance Score**: 67/100 (Needs Improvement)

**Key Findings**:
- Build time: 142s (Target: <60s) - 58% slower
- Bundle size: 1.2 MB gzipped (Target: <200 KB) - 6x over
- LCP: 3.8s (Target: <2.5s) - Poor
- API p95: 847ms (Target: <500ms) - Slow

**Estimated Impact of Recommendations**:
- Build time: -65s (46% improvement)
- Bundle size: -800 KB (67% reduction)
- LCP: -1.5s (39% improvement)
- API p95: -400ms (47% improvement)

## Critical Bottlenecks

### [PERF-001] Lodash Full Library Import
**Category**: Bundle Size
**Impact**: HIGH
**Effort**: LOW

**Issue**: Full lodash library imported, adding 71 KB to bundle.

**Current**:

import _ from 'lodash';

const result = _.debounce(handler, 300);


**Problem**: Imports entire library for single function.

**Recommendation**: Use lodash-es with tree-shaking.

**Optimized**:

import { debounce } from 'lodash-es';

const result = debounce(handler, 300);


**Savings**: -65 KB gzipped

---

### [PERF-002] Moment.js for Simple Date Formatting
**Category**: Bundle Size
**Impact**: MEDIUM
**Effort**: LOW

**Issue**: moment.js adds 67 KB for basic date formatting.

**Current**:

import moment from 'moment';

const formatted = moment(date).format('YYYY-MM-DD');


**Recommendation**: Replace with date-fns or native Intl.

**Optimized**:

import { format } from 'date-fns';

const formatted = format(date, 'yyyy-MM-dd');


**Savings**: -60 KB gzipped

---

### [PERF-003] TypeScript Compilation Bottleneck
**Category**: Build Time
**Impact**: HIGH
**Effort**: MEDIUM

**Issue**: TypeScript taking 89s of 142s build time (63%).

**Current Config**:

{

"compilerOptions": {

"incremental": false,

"skipLibCheck": false

}

}


**Problems**:
- No incremental compilation
- Checking all .d.ts files
- No build cache

**Optimized**:

{

"compilerOptions": {

"incremental": true,

"skipLibCheck": true,

"tsBuildInfoFile": ".tsbuildinfo"

}

}


**Savings**: -45s build time (first build), -70s (subsequent)

---

### [PERF-004] N+1 Query in User Profile API
**Category**: API Performance
**Impact**: CRITICAL
**Effort**: LOW

**Issue**: Loading user posts in a loop, causing 100+ database queries.

**Current**:

const users = await db.getUsers();

for (const user of users) {

user.posts = await db.getPostsByUserId(user.id); // N+1!

}


**Problem**: 1 query + N queries = 101 total for 100 users.

**Optimized**:

const users = await db.getUsers();

const userIds = users.map(u => u.id);

const posts = await db.getPostsByUserIds(userIds); // 1 query

const postsByUser = groupBy(posts, 'userId');

users.forEach(user => {

user.posts = postsByUser[user.id] || [];

});


**Savings**: 99 database queries eliminated, 95% faster

## Build Performance Analysis

### Current Build Breakdown

Total Build Time: 142s

Phase Breakdown:

├── Dependencies (npm install): 23s (16%)

├── TypeScript Compilation: 89s (63%)

├── Asset Processing: 18s (13%)

├── Bundling (Webpack): 9s (6%)

└── Minification: 3s (2%)

Bottleneck: TypeScript (63% of time)


### Optimization Recommendations

**1. Enable Incremental TypeScript** (HIGH IMPACT)
- Savings: -70s on subsequent builds
- Add `incremental: true` to tsconfig.json

**2. Parallelize Asset Processing** (MEDIUM IMPACT)
- Savings: -10s
- Use worker threads for image optimization

**3. Use SWC Instead of Babel** (MEDIUM IMPACT)
- Savings: -5s
- 20x faster than Babel

**Total Potential Savings**: -85s (60% improvement)

**Target Build Time**: 57s

## Bundle Size Analysis

### Current Bundle Breakdown

Total Bundle Size: 1.2 MB gzipped

Dependencies:

├── react + react-dom: 142 KB (12%)

├── lodash: 71 KB (6%)

├── moment: 67 KB (6%)

├── chart.js: 54 KB (5%)

├── Other vendor: 445 KB (37%)

└── Application code: 421 KB (34%)

Issues:


### Optimization Recommendations

**1. Replace Heavy Dependencies** (HIGH IMPACT)
- lodash → lodash-es: -65 KB
- moment → date-fns: -60 KB
- chart.js → lightweight-charts: -40 KB
- Total: -165 KB (14% reduction)

**2. Code Splitting** (HIGH IMPACT)
- Lazy load admin panel: -200 KB from initial
- Lazy load dashboard charts: -150 KB from initial
- Total: -350 KB from initial load (29% reduction)

**3. Tree Shaking Improvements** (MEDIUM IMPACT)
- Fix sideEffects in package.json
- Remove unused exports
- Estimated: -100 KB (8% reduction)

**Total Potential Savings**: -615 KB (51% reduction)

**Target Bundle Size**: 585 KB gzipped

## Runtime Performance Analysis

### Core Web Vitals

Current Performance:

Time to Interactive: 5.2s (Poor) - Target: <3.5s


### Bottlenecks Identified

**1. Large Initial JavaScript Bundle** (CRITICAL)
- 1.2 MB blocks rendering
- Recommendation: Code split, lazy load

**2. Heavy Initial Data Fetch** (HIGH)
- 847 KB JSON downloaded before first paint
- Recommendation: Pagination, defer non-critical data

**3. Expensive Re-renders** (MEDIUM)
- UserList component re-renders 47 times on page load
- Recommendation: React.memo, useMemo

## API Performance Analysis

### Slow Endpoints

Top 5 Slowest Endpoints (p95):

  1. GET /api/users (with posts)
  1. GET /api/dashboard
  1. POST /api/orders
  1. GET /api/reports/monthly
  1. GET /api/search

### Database Query Optimization

**Missing Indexes Detected**:

-- Query: SELECT * FROM orders WHERE user_id = ? AND status = 'pending'

-- Execution time: 847ms (table scan)

-- Recommendation: Add composite index

CREATE INDEX idx_orders_user_status ON orders(user_id, status);

-- Estimated improvement: 98% faster (15ms)


## Memory Usage Analysis

### Memory Leaks Detected

**1. Event Listener Not Cleaned Up** (HIGH)

// Leak in useEffect

useEffect(() => {

window.addEventListener('resize', handleResize);

// Missing cleanup!

});

// Fix:

useEffect(() => {

window.addEventListener('resize', handleResize);

return () => window.removeEventListener('resize', handleResize);

}, []);


**2. Growing Cache Without Limits** (MEDIUM)

// Unbounded cache grows forever

const cache = new Map();

function memoize(key, fn) {

if (!cache.has(key)) {

cache.set(key, fn());

}

return cache.get(key);

}

// Fix: Use LRU cache with size limit

import LRU from 'lru-cache';

const cache = new LRU({ max: 500 });


## Optimization Priority Matrix

Impact vs Effort:

HIGH IMPACT, LOW EFFORT (Do First):

HIGH IMPACT, MEDIUM EFFORT (Do Soon):

MEDIUM IMPACT, LOW EFFORT (Quick Wins):

LOW PRIORITY:


## Recommendations Summary

### Immediate Actions (This Week)

1. Fix N+1 query in /api/users
2. Replace lodash with lodash-es
3. Enable TypeScript incremental
4. Add database index for orders query

**Expected Impact**: 40% performance improvement

### Short Term (This Month)

1. Implement code splitting
2. Replace moment.js with date-fns
3. Lazy load admin panel
4. Add React.memo to UserList

**Expected Impact**: Additional 30% improvement

### Long Term (This Quarter)

1. Implement caching layer (Redis)
2. Add CDN for static assets
3. Database query optimization audit
4. Consider server-side rendering

**Expected Impact**: Additional 20% improvement

**Total Expected Improvement**: 90% (Score: 67 → 127)

Integration with Dev Plugin

With Audit Skill

Combine performance and security:

Run optimization analysis and check performance implications of security fixes

With Test Coverage

Ensure optimizations don't break functionality:

Optimize bundle size and verify test coverage remains above 80%

With Code Analysis

Use enrichment for better context:

Enrich codebase with claudemem, then identify performance bottlenecks

Best Practices

1. Measure Before Optimizing

Always establish baseline:

Anti-pattern: Optimizing without measuring

2. Focus on User-Perceived Performance

Prioritize metrics that affect users:

Anti-pattern: Optimizing server metrics that users don't notice

3. Optimize the Critical Path

Focus on:

Anti-pattern: Optimizing rarely-used features

4. Use Performance Budgets

Set hard limits:

Enforcement: CI/CD checks fail if exceeded

5. Monitor in Production

Use real user monitoring (RUM):

Tools: Lighthouse CI, Sentry, DataDog

Examples

Example 1: Slow React Application

Request:

Our React app takes 8 seconds to load. Please identify bottlenecks.

Analysis Process:

  1. Measure bundle size: 2.1 MB gzipped
  2. Analyze bundle composition
  3. Profile React rendering
  4. Check network waterfall

Findings:

Optimizations:

// 1. Code splitting
const AdminPanel = lazy(() => import('./AdminPanel'));

// 2. Tree-shakeable imports
import Button from '@mui/material/Button'; // Not: import { Button } from '@mui/material';

// 3. Pagination
const users = await fetchUsers({ page: 1, limit: 20 }); // Not: all users

// 4. Memoization
const UserList = React.memo(({ users }) => { ... });

Results:

Example 2: Slow TypeScript Build

Request:

TypeScript compilation takes 3 minutes. Speed it up.

Analysis:

  1. Profile build with --extendedDiagnostics
  2. Identify slow files
  3. Check tsconfig.json

Findings:

Optimizations:

{
  "compilerOptions": {
    "incremental": true,
    "tsBuildInfoFile": ".tsbuildinfo",
    "skipLibCheck": true,
    "isolatedModules": true
  },
  "exclude": ["node_modules", "dist"]
}

Results:

Example 3: Database Query Optimization

Request:

The /api/orders endpoint is timing out under load

Analysis:

  1. Enable query logging
  2. Identify slow queries
  3. Analyze query plans
  4. Check for missing indexes

Findings:

-- Slow query (12s for 1M rows)
SELECT * FROM orders
WHERE user_id = 12345
  AND status IN ('pending', 'processing')
  AND created_at > '2026-01-01'
ORDER BY created_at DESC
LIMIT 20;

-- Query plan: FULL TABLE SCAN (bad)

Optimization:

-- Add composite index
CREATE INDEX idx_orders_user_status_date
ON orders(user_id, status, created_at);

-- Query plan now: INDEX SCAN (good)
-- Execution time: 12s → 23ms (99.8% faster)

Stack-Specific Optimization Patterns

React/TypeScript

Common Bottlenecks:

Optimization Tools:

Go

Common Bottlenecks:

Optimization Tools:

Rust

Common Bottlenecks:

Optimization Tools:

Conclusion

The optimize skill provides comprehensive performance analysis and actionable recommendations. Use it regularly to maintain optimal performance, reduce costs, and improve user experience.

Key Takeaways:

For security analysis, see the audit skill. For test gaps, see the test-coverage skill.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.