Performance Optimization with AI Assistance
Use AI to identify and fix performance bottlenecks in your code. Learn practical techniques for faster, more efficient applications.
Performance Optimization with AI Assistance
Performance issues can be elusive and time-consuming to diagnose. AI assistants excel at analyzing code patterns, identifying bottlenecks, and suggesting optimizations. This guide shows you how to leverage AI for performance work.
AI-Assisted Performance Analysis
Requesting a Performance Review
You: Analyze this function for performance issues:
function processOrders(orders) {
const results = [];
for (const order of orders) {
const user = users.find(u => u.id === order.userId);
const products = order.items.map(item =>
products.find(p => p.id === item.productId)
);
results.push({ order, user, products });
}
return results;
}
Claude: I've identified several performance issues:
1. **O(n²) complexity** - `users.find()` inside loop
2. **O(n³) complexity** - nested `products.find()` inside map
3. **No early termination** - processes all orders even if limit needed
Here's an optimized version with O(n) complexity...
Using the /perf Skill
hljs bash# Analyze a file
/perf src/services/orderService.js
# Analyze with specific focus
/perf --focus memory src/utils/dataProcessor.js
# Generate performance report
/perf --report src/
Common Performance Patterns
Pattern 1: Loop Optimization
Before (O(n²)):
hljs javascriptfunction findMatches(items, targets) {
return items.filter(item =>
targets.includes(item.id) // O(n) for each item
);
}
After (O(n)):
hljs javascriptfunction findMatches(items, targets) {
const targetSet = new Set(targets); // O(n) once
return items.filter(item =>
targetSet.has(item.id) // O(1) for each item
);
}
Pattern 2: Memoization
Before:
hljs javascriptfunction fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// fibonacci(40) takes ~1 second
After:
hljs javascriptfunction fibonacci(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 1) return n;
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo);
return memo[n];
}
// fibonacci(40) takes ~0.001ms
Pattern 3: Lazy Loading
Before:
hljs javascript// Loads everything upfront
import { Chart, Table, Form, Modal, DatePicker } from 'heavy-ui-lib';
After:
hljs javascript// Load only when needed
const Chart = lazy(() => import('heavy-ui-lib/Chart'));
const Table = lazy(() => import('heavy-ui-lib/Table'));
Pattern 4: Database Query Optimization
Before (N+1 problem):
hljs javascriptconst orders = await Order.findAll();
for (const order of orders) {
order.user = await User.findById(order.userId); // N queries
}
After (eager loading):
hljs javascriptconst orders = await Order.findAll({
include: [{ model: User, as: 'user' }] // 1 query with JOIN
});
React Performance Optimization
Identifying Re-render Issues
Ask Claude to analyze component renders:
You: Why might this component be re-rendering excessively?
function ProductList({ products, onSelect }) {
return (
<ul>
{products.map(product => (
<ProductItem
key={product.id}
product={product}
onClick={() => onSelect(product.id)}
/>
))}
</ul>
);
}
Optimization Techniques
1. Memoize callbacks:
hljs jsxfunction ProductList({ products, onSelect }) {
const handleClick = useCallback((id) => {
onSelect(id);
}, [onSelect]);
return (
<ul>
{products.map(product => (
<ProductItem
key={product.id}
product={product}
onClick={handleClick}
/>
))}
</ul>
);
}
2. Memoize components:
hljs jsxconst ProductItem = memo(function ProductItem({ product, onClick }) {
return (
<li onClick={() => onClick(product.id)}>
{product.name}
</li>
);
});
3. Virtualize long lists:
hljs jsximport { FixedSizeList } from 'react-window';
function ProductList({ products }) {
return (
<FixedSizeList
height={400}
itemCount={products.length}
itemSize={50}
>
{({ index, style }) => (
<div style={style}>
{products[index].name}
</div>
)}
</FixedSizeList>
);
}
Backend Performance
API Response Optimization
You: How can I optimize this API endpoint that's taking 2+ seconds?
async function getOrderDetails(orderId) {
const order = await Order.findById(orderId);
const user = await User.findById(order.userId);
const items = await OrderItem.findAll({ orderId });
const products = await Promise.all(
items.map(item => Product.findById(item.productId))
);
return { order, user, items, products };
}
Optimized version:
hljs javascriptasync function getOrderDetails(orderId) {
// Parallel queries where possible
const [order, items] = await Promise.all([
Order.findById(orderId, {
include: [{ model: User, as: 'user' }]
}),
OrderItem.findAll({
where: { orderId },
include: [{ model: Product, as: 'product' }]
})
]);
return {
order,
user: order.user,
items: items.map(item => ({
...item,
product: item.product
}))
};
}
// Reduced from 5 queries to 2
Caching Strategies
hljs javascript// Ask Claude to implement caching
const cache = new Map();
const CACHE_TTL = 60000; // 1 minute
async function getCachedUser(userId) {
const cacheKey = `user:${userId}`;
const cached = cache.get(cacheKey);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.data;
}
const user = await User.findById(userId);
cache.set(cacheKey, { data: user, timestamp: Date.now() });
return user;
}
Performance Profiling with AI
Interpreting Profiler Output
You: Here's my Chrome DevTools performance profile summary.
What should I focus on?
- Scripting: 2,450ms
- Rendering: 890ms
- Painting: 120ms
- System: 340ms
- Idle: 1,200ms
Top functions by self time:
1. processData: 890ms
2. renderChart: 450ms
3. JSON.parse: 380ms
4. calculateTotals: 290ms
Claude: Based on this profile, I recommend focusing on:
1. **processData (890ms)** - This is your biggest bottleneck.
Consider web workers or chunking for large datasets.
2. **JSON.parse (380ms)** - Large JSON payloads.
Consider streaming JSON parsing or pagination.
3. **renderChart (450ms)** - Chart rendering is expensive.
Consider canvas-based charts or reducing data points.
Memory Leak Detection
You: My app's memory usage grows over time. How can I find the leak?
Claude: Here's a systematic approach:
1. **Take heap snapshots** at intervals
2. **Compare snapshots** to find growing objects
3. **Check for common causes:**
- Event listeners not removed
- Closures holding references
- Timers not cleared
- DOM nodes not removed
Let me analyze your code for potential leaks...
Performance Testing
Load Testing with AI
You: Generate a load test for my API using k6
Claude: Here's a comprehensive load test:
hljs javascript// load-test.js
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
stages: [
{ duration: '30s', target: 20 }, // Ramp up
{ duration: '1m', target: 20 }, // Stay at 20
{ duration: '30s', target: 50 }, // Ramp to 50
{ duration: '1m', target: 50 }, // Stay at 50
{ duration: '30s', target: 0 }, // Ramp down
],
thresholds: {
http_req_duration: ['p(95)<500'], // 95% under 500ms
http_req_failed: ['rate<0.01'], // <1% errors
},
};
export default function () {
const res = http.get('https://api.example.com/orders');
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
sleep(1);
}
Benchmark Generation
hljs bash# Generate benchmarks for a function
/perf --benchmark src/utils/dataTransform.js
Performance Checklist
Frontend
- Bundle size analyzed and optimized
- Images optimized and lazy-loaded
- Code splitting implemented
- Critical CSS inlined
- Service worker for caching
- Virtual scrolling for long lists
Backend
- Database queries optimized (no N+1)
- Appropriate indexes created
- Response caching implemented
- Connection pooling configured
- Async operations parallelized
- Payload sizes minimized
Infrastructure
- CDN configured for static assets
- Gzip/Brotli compression enabled
- HTTP/2 or HTTP/3 enabled
- Database connection limits set
- Auto-scaling configured
Conclusion
AI assistants are powerful allies in performance optimization. They can:
- Quickly identify common anti-patterns
- Suggest proven optimization techniques
- Generate performance tests
- Interpret profiling data
The key is providing enough context about your performance goals and constraints.
Next: Explore Team Collaboration to share performance best practices across your team.
Related Articles
Security Best Practices for AI-Assisted Development
Essential security guidelines for using AI coding assistants safely. Protect your codebase, credentials, and sensitive data.