Performance optimizer skill

Identifies and fixes performance bottlenecks in code, databases, and APIs.

by davila7·MIT license·★ 32,299 Stars on the repo·GitHub ↗

Use now

Files of Performance optimizer

davila7/main1 file shown
SKILL.md
Show the full text390 lines

Performance Optimizer

Find and fix performance bottlenecks. Measure, optimize, verify. Make it fast.

When to Use This Skill

  • App is slow or laggy
  • User complains about performance
  • Page load times are high
  • API responses are slow
  • Database queries take too long
  • User mentions "slow", "lag", "performance", or "optimize"

The Optimization Process

1. Measure First

Never optimize without measuring:

// Measure execution time
console.time('operation');
await slowOperation();
console.timeEnd('operation'); // operation: 2341ms

What to measure:

  • Page load time
  • API response time
  • Database query time
  • Function execution time
  • Memory usage
  • Network requests
2. Find the Bottleneck

Use profiling tools to find the slow parts:

Browser:

DevTools → Performance tab → Record → Stop
Look for long tasks (red bars)

Node.js:

node --prof app.js
node --prof-process isolate-*.log > profile.txt

Database:

EXPLAIN ANALYZE SELECT * FROM users WHERE email = '[email protected]';
3. Optimize

Fix the slowest thing first (biggest impact).

Common Optimizations

Database Queries

Problem: N+1 Queries

// Bad: N+1 queries
const users = await db.users.find();
for (const user of users) {
  user.posts = await db.posts.find({ userId: user.id }); // N queries
}

// Good: Single query with JOIN
const users = await db.users.find()
  .populate('posts'); // 1 query

Problem: Missing Index

-- Check slow query
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
-- Shows: Seq Scan (bad)

-- Add index
CREATE INDEX idx_users_email ON users(email);

-- Check again
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
-- Shows: Index Scan (good)

**Problem: SELECT ***

// Bad: Fetches all columns
const users = await db.query('SELECT * FROM users');

// Good: Only needed columns
const users = await db.query('SELECT id, name, email FROM users');

Problem: No Pagination

// Bad: Returns all records
const users = await db.users.find();

// Good: Paginated
const users = await db.users.find()
  .limit(20)
  .skip((page - 1) * 20);
API Performance

Problem: No Caching

// Bad: Hits database every time
app.get('/api/stats', async (req, res) => {
  const stats = await db.stats.calculate(); // Slow
  res.json(stats);
});

// Good: Cache for 5 minutes
const cache = new Map();
app.get('/api/stats', async (req, res) => {
  const cached = cache.get('stats');
  if (cached && Date.now() - cached.time < 300000) {
    return res.json(cached.data);
  }
  
  const stats = await db.stats.calculate();
  cache.set('stats', { data: stats, time: Date.now() });
  res.json(stats);
});

Problem: Sequential Operations

// Bad: Sequential (slow)
const user = await getUser(id);
const posts = await getPosts(id);
const comments = await getComments(id);
// Total: 300ms + 200ms + 150ms = 650ms

// Good: Parallel (fast)
const [user, posts, comments] = await Promise.all([
  getUser(id),
  getPosts(id),
  getComments(id)
]);
// Total: max(300ms, 200ms, 150ms) = 300ms

Problem: Large Payloads

// Bad: Returns everything
res.json(users); // 5MB response

// Good: Only needed fields
res.json(users.map(u => ({
  id: u.id,
  name: u.name,
  email: u.email
}))); // 500KB response
Frontend Performance

Problem: Unnecessary Re-renders

// Bad: Re-renders on every parent update
function UserList({ users }) {
  return users.map(user => <UserCard user={user} />);
}

// Good: Memoized
const UserCard = React.memo(({ user }) => {
  return <div>{user.name}</div>;
});

Problem: Large Bundle

// Bad: Imports entire library
import _ from 'lodash'; // 70KB

// Good: Import only what you need
import debounce from 'lodash/debounce'; // 2KB

Problem: No Code Splitting

// Bad: Everything in one bundle
import HeavyComponent from './HeavyComponent';

// Good: Lazy load
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));

Problem: Unoptimized Images

<!-- Bad: Large image -->
<img src="photo.jpg" /> <!-- 5MB -->

<!-- Good: Optimized and responsive -->
<img 
  src="photo-small.webp" 
  srcset="photo-small.webp 400w, photo-large.webp 800w"
  loading="lazy"
  width="400"
  height="300"
/> <!-- 50KB -->
Algorithm Optimization

Problem: Inefficient Algorithm

// Bad: O(n²) - nested loops
function findDuplicates(arr) {
  const duplicates = [];
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] === arr[j]) duplicates.push(arr[i]);
    }
  }
  return duplicates;
}

// Good: O(n) - single pass with Set
function findDuplicates(arr) {
  const seen = new Set();
  const duplicates = new Set();
  for (const item of arr) {
    if (seen.has(item)) duplicates.add(item);
    seen.add(item);
  }
  return Array.from(duplicates);
}

Problem: Repeated Calculations

// Bad: Calculates every time
function getTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
// Called 100 times in render

// Good: Memoized
const getTotal = useMemo(() => {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}, [items]);
Memory Optimization

Problem: Memory Leak

// Bad: Event listener not cleaned up
useEffect(() => {
  window.addEventListener('scroll', handleScroll);
  // Memory leak!
}, []);

// Good: Cleanup
useEffect(() => {
  window.addEventListener('scroll', handleScroll);
  return () => window.removeEventListener('scroll', handleScroll);
}, []);

Problem: Large Data in Memory

// Bad: Loads entire file into memory
const data = fs.readFileSync('huge-file.txt'); // 1GB

// Good: Stream it
const stream = fs.createReadStream('huge-file.txt');
stream.on('data', chunk => process(chunk));

Measuring Impact

Always measure before and after:

// Before optimization
console.time('query');
const users = await db.users.find();
console.timeEnd('query');
// query: 2341ms

// After optimization (added index)
console.time('query');
const users = await db.users.find();
console.timeEnd('query');
// query: 23ms

// Improvement: 100x faster!

Performance Budgets

Set targets:

Page Load: < 2 seconds
API Response: < 200ms
Database Query: < 50ms
Bundle Size: < 200KB
Time to Interactive: < 3 seconds

Tools

Browser:

  • Chrome DevTools Performance tab
  • Lighthouse (audit)
  • Network tab (waterfall)

Node.js:

  • node --prof (profiling)
  • clinic (diagnostics)
  • autocannon (load testing)

Database:

  • EXPLAIN ANALYZE (query plans)
  • Slow query log
  • Database profiler

Monitoring:

  • New Relic
  • Datadog
  • Sentry Performance

Quick Wins

Easy optimizations with big impact:

  1. Add database indexes on frequently queried columns
  2. Enable gzip compression on server
  3. Add caching for expensive operations
  4. Lazy load images and heavy components
  5. Use CDN for static assets
  6. Minify and compress JavaScript/CSS
  7. Remove unused dependencies
  8. Use pagination instead of loading all data
  9. Optimize images (WebP, proper sizing)
  10. Enable HTTP/2 on server

Optimization Checklist

  • Measured current performance
  • Identified bottleneck
  • Applied optimization
  • Measured improvement
  • Verified functionality still works
  • No new bugs introduced
  • Documented the change

When NOT to Optimize

  • Premature optimization (optimize when it's actually slow)
  • Micro-optimizations (save 1ms when page takes 5 seconds)
  • Readable code is more important than tiny speed gains
  • If it's already fast enough

Key Principles

  • Measure before optimizing
  • Fix the biggest bottleneck first
  • Measure after to prove improvement
  • Don't sacrifice readability for tiny gains
  • Profile in production-like environment
  • Consider the 80/20 rule (20% of code causes 80% of slowness)
  • @database-design - Query optimization
  • @codebase-audit-pre-push - Code review
  • @bug-hunter - Debugging
1---
2name: performance-optimizer
3description: "Identifies and fixes performance bottlenecks in code, databases, and APIs. Measures before and after to prove improvements."
4category: development
5risk: safe
6source: community
7date_added: "2026-03-05"
8---
9 
10# Performance Optimizer
11 
12Find and fix performance bottlenecks. Measure, optimize, verify. Make it fast.
13 
14## When to Use This Skill
15 
16- App is slow or laggy
17- User complains about performance
18- Page load times are high
19- API responses are slow
20- Database queries take too long
21- User mentions "slow", "lag", "performance", or "optimize"
22 
23## The Optimization Process
24 
25### 1. Measure First
26 
27Never optimize without measuring:
28 
29```javascript
30// Measure execution time
31console.time('operation');
32await slowOperation();
33console.timeEnd('operation'); // operation: 2341ms
34```
35 
36**What to measure:**
37- Page load time
38- API response time
39- Database query time
40- Function execution time
41- Memory usage
42- Network requests
43 
44### 2. Find the Bottleneck
45 
46Use profiling tools to find the slow parts:
47 
48**Browser:**
49```
50DevTools → Performance tab → Record → Stop
51Look for long tasks (red bars)
52```
53 
54**Node.js:**
55```bash
56node --prof app.js
57node --prof-process isolate-*.log > profile.txt
58```
59 
60**Database:**
61```sql
62EXPLAIN ANALYZE SELECT * FROM users WHERE email = '[email protected]';
63```
64 
65### 3. Optimize
66 
67Fix the slowest thing first (biggest impact).
68 
69## Common Optimizations
70 
71### Database Queries
72 
73**Problem: N+1 Queries**
74```javascript
75// Bad: N+1 queries
76const users = await db.users.find();
77for (const user of users) {
78 user.posts = await db.posts.find({ userId: user.id }); // N queries
79}
80 
81// Good: Single query with JOIN
82const users = await db.users.find()
83 .populate('posts'); // 1 query
84```
85 
86**Problem: Missing Index**
87```sql
88-- Check slow query
89EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
90-- Shows: Seq Scan (bad)
91 
92-- Add index
93CREATE INDEX idx_users_email ON users(email);
94 
95-- Check again
96EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
97-- Shows: Index Scan (good)
98```
99 
100**Problem: SELECT ***
101```javascript
102// Bad: Fetches all columns
103const users = await db.query('SELECT * FROM users');
104 
105// Good: Only needed columns
106const users = await db.query('SELECT id, name, email FROM users');
107```
108 
109**Problem: No Pagination**
110```javascript
111// Bad: Returns all records
112const users = await db.users.find();
113 
114// Good: Paginated
115const users = await db.users.find()
116 .limit(20)
117 .skip((page - 1) * 20);
118```
119 
120### API Performance
121 
122**Problem: No Caching**
123```javascript
124// Bad: Hits database every time
125app.get('/api/stats', async (req, res) => {
126 const stats = await db.stats.calculate(); // Slow
127 res.json(stats);
128});
129 
130// Good: Cache for 5 minutes
131const cache = new Map();
132app.get('/api/stats', async (req, res) => {
133 const cached = cache.get('stats');
134 if (cached && Date.now() - cached.time < 300000) {
135 return res.json(cached.data);
136 }
137 
138 const stats = await db.stats.calculate();
139 cache.set('stats', { data: stats, time: Date.now() });
140 res.json(stats);
141});
142```
143 
144**Problem: Sequential Operations**
145```javascript
146// Bad: Sequential (slow)
147const user = await getUser(id);
148const posts = await getPosts(id);
149const comments = await getComments(id);
150// Total: 300ms + 200ms + 150ms = 650ms
151 
152// Good: Parallel (fast)
153const [user, posts, comments] = await Promise.all([
154 getUser(id),
155 getPosts(id),
156 getComments(id)
157]);
158// Total: max(300ms, 200ms, 150ms) = 300ms
159```
160 
161**Problem: Large Payloads**
162```javascript
163// Bad: Returns everything
164res.json(users); // 5MB response
165 
166// Good: Only needed fields
167res.json(users.map(u => ({
168 id: u.id,
169 name: u.name,
170 email: u.email
171}))); // 500KB response
172```
173 
174### Frontend Performance
175 
176**Problem: Unnecessary Re-renders**
177```javascript
178// Bad: Re-renders on every parent update
179function UserList({ users }) {
180 return users.map(user => <UserCard user={user} />);
181}
182 
183// Good: Memoized
184const UserCard = React.memo(({ user }) => {
185 return <div>{user.name}</div>;
186});
187```
188 
189**Problem: Large Bundle**
190```javascript
191// Bad: Imports entire library
192import _ from 'lodash'; // 70KB
193 
194// Good: Import only what you need
195import debounce from 'lodash/debounce'; // 2KB
196```
197 
198**Problem: No Code Splitting**
199```javascript
200// Bad: Everything in one bundle
201import HeavyComponent from './HeavyComponent';
202 
203// Good: Lazy load
204const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
205```
206 
207**Problem: Unoptimized Images**
208```html
209<!-- Bad: Large image -->
210<img src="photo.jpg" /> <!-- 5MB -->
211 
212<!-- Good: Optimized and responsive -->
213<img
214 src="photo-small.webp"
215 srcset="photo-small.webp 400w, photo-large.webp 800w"
216 loading="lazy"
217 width="400"
218 height="300"
219/> <!-- 50KB -->
220```
221 
222### Algorithm Optimization
223 
224**Problem: Inefficient Algorithm**
225```javascript
226// Bad: O(n²) - nested loops
227function findDuplicates(arr) {
228 const duplicates = [];
229 for (let i = 0; i < arr.length; i++) {
230 for (let j = i + 1; j < arr.length; j++) {
231 if (arr[i] === arr[j]) duplicates.push(arr[i]);
232 }
233 }
234 return duplicates;
235}
236 
237// Good: O(n) - single pass with Set
238function findDuplicates(arr) {
239 const seen = new Set();
240 const duplicates = new Set();
241 for (const item of arr) {
242 if (seen.has(item)) duplicates.add(item);
243 seen.add(item);
244 }
245 return Array.from(duplicates);
246}
247```
248 
249**Problem: Repeated Calculations**
250```javascript
251// Bad: Calculates every time
252function getTotal(items) {
253 return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
254}
255// Called 100 times in render
256 
257// Good: Memoized
258const getTotal = useMemo(() => {
259 return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
260}, [items]);
261```
262 
263### Memory Optimization
264 
265**Problem: Memory Leak**
266```javascript
267// Bad: Event listener not cleaned up
268useEffect(() => {
269 window.addEventListener('scroll', handleScroll);
270 // Memory leak!
271}, []);
272 
273// Good: Cleanup
274useEffect(() => {
275 window.addEventListener('scroll', handleScroll);
276 return () => window.removeEventListener('scroll', handleScroll);
277}, []);
278```
279 
280**Problem: Large Data in Memory**
281```javascript
282// Bad: Loads entire file into memory
283const data = fs.readFileSync('huge-file.txt'); // 1GB
284 
285// Good: Stream it
286const stream = fs.createReadStream('huge-file.txt');
287stream.on('data', chunk => process(chunk));
288```
289 
290## Measuring Impact
291 
292Always measure before and after:
293 
294```javascript
295// Before optimization
296console.time('query');
297const users = await db.users.find();
298console.timeEnd('query');
299// query: 2341ms
300 
301// After optimization (added index)
302console.time('query');
303const users = await db.users.find();
304console.timeEnd('query');
305// query: 23ms
306 
307// Improvement: 100x faster!
308```
309 
310## Performance Budgets
311 
312Set targets:
313 
314```
315Page Load: < 2 seconds
316API Response: < 200ms
317Database Query: < 50ms
318Bundle Size: < 200KB
319Time to Interactive: < 3 seconds
320```
321 
322## Tools
323 
324**Browser:**
325- Chrome DevTools Performance tab
326- Lighthouse (audit)
327- Network tab (waterfall)
328 
329**Node.js:**
330- `node --prof` (profiling)
331- `clinic` (diagnostics)
332- `autocannon` (load testing)
333 
334**Database:**
335- `EXPLAIN ANALYZE` (query plans)
336- Slow query log
337- Database profiler
338 
339**Monitoring:**
340- New Relic
341- Datadog
342- Sentry Performance
343 
344## Quick Wins
345 
346Easy optimizations with big impact:
347 
3481. **Add database indexes** on frequently queried columns
3492. **Enable gzip compression** on server
3503. **Add caching** for expensive operations
3514. **Lazy load** images and heavy components
3525. **Use CDN** for static assets
3536. **Minify and compress** JavaScript/CSS
3547. **Remove unused dependencies**
3558. **Use pagination** instead of loading all data
3569. **Optimize images** (WebP, proper sizing)
35710. **Enable HTTP/2** on server
358 
359## Optimization Checklist
360 
361- [ ] Measured current performance
362- [ ] Identified bottleneck
363- [ ] Applied optimization
364- [ ] Measured improvement
365- [ ] Verified functionality still works
366- [ ] No new bugs introduced
367- [ ] Documented the change
368 
369## When NOT to Optimize
370 
371- Premature optimization (optimize when it's actually slow)
372- Micro-optimizations (save 1ms when page takes 5 seconds)
373- Readable code is more important than tiny speed gains
374- If it's already fast enough
375 
376## Key Principles
377 
378- Measure before optimizing
379- Fix the biggest bottleneck first
380- Measure after to prove improvement
381- Don't sacrifice readability for tiny gains
382- Profile in production-like environment
383- Consider the 80/20 rule (20% of code causes 80% of slowness)
384 
385## Related Skills
386 
387- `@database-design` - Query optimization
388- `@codebase-audit-pre-push` - Code review
389- `@bug-hunter` - Debugging
390 

Discussion

Alternatives

Skill CreatorCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Coding · Apache-2.0Professional Full-Stack Developer for Network Mapping & Monitoring ApplicationAct as a professional full-stack developer tasked with building a web application for mapping and monitoring networks using Mikrotik Netwatch API. Implement multi-user role-based management to handle devices, monitor their status, and manage user subscriptions.Coding · CC0-1.0Prompt refinerHigh-end Prompt Engineering & Prompt Refiner skill. Transforms raw or messy user requests into concise, token-efficient, high-performance master prompts for systems like GPT, Claude, and Gemini. Use when you want to optimize or redesign a prompt so it solves the problem reliably while minimizing tokens.Data & AI · CC0-1.0Constraint driven developmentEstablishes a project's quality bar as a written contract and stops agents quietly lowering it. Interviews the user on which dimensions matter, supplies sane default thresholds when they have no number in mind, records everything in CONSTRAINTS.md, and watches the diff for a weakened bar — new @ts-ignore or eslint-disable suppressions, skipped or deleted tests, assertions stripped out, unimplemented stubs, thresholds edited down. Use when no quality bar is written down, when the user says "set up constraints" or "define our standards", when the user wants dimensions they care about — accessibility, web performance, coverage — set up as enforced constraints, when an agent keeps silencing checks or skipping tests to get to green, when you need a coverage or performance threshold and don't know what number to pick, or when an agent writes more code than anyone will read.Coding · MIT