optimize
Analyzes code for performance issues including slow algorithms, memory leaks, unnecessary re-renders, database query problems, and resource bottlenecks. Use when the user says "this is slow", "optimize this", "performance issue", "why is this taking so long?", or "make this faster".
What this skill does
# Performance Optimization Skill
When analyzing code for performance, follow this structured process:
## 1. Understand What's Slow
- Ask or determine: what operation is slow? (page load, API response, build time, query, render)
- What's the current performance? (response time, load time, memory usage)
- What's the expected/acceptable performance?
- How much data is involved? (10 rows vs 10 million rows changes everything)
## 2. Algorithm & Data Structure Analysis
- Identify time complexity of key operations (O(n), O(nยฒ), O(n log n), etc.)
- Look for nested loops over large datasets
- Check if a different data structure would help:
- Array lookups that should be Map/Set/Object for O(1) access
- Linear searches that should use binary search or indexing
- Repeated array filtering that should be pre-grouped
- Look for unnecessary sorting or repeated work
Flag pattern:
```
// ๐ด BAD โ O(nยฒ): nested loop for lookups
users.forEach(user => {
const order = orders.find(o => o.userId === user.id);
});
// โ
GOOD โ O(n): pre-index with Map
const orderMap = new Map(orders.map(o => [o.userId, o]));
users.forEach(user => {
const order = orderMap.get(user.id);
});
```
## 3. Database & Query Performance
- **N+1 queries**: Loading related data inside a loop instead of batch loading
- **Missing indexes**: Queries filtering/sorting on unindexed columns
- **Over-fetching**: SELECT * when only a few columns are needed
- **Missing pagination**: Loading entire tables into memory
- **Unoptimized joins**: Joining large tables without proper conditions
- **Missing connection pooling**: Opening new connections per request
Flag pattern:
```
// ๐ด BAD โ N+1: one query per user
for (const user of users) {
const posts = await db.query('SELECT * FROM posts WHERE user_id = ?', [user.id]);
}
// โ
GOOD โ single batch query
const posts = await db.query('SELECT * FROM posts WHERE user_id IN (?)', [userIds]);
const postsByUser = groupBy(posts, 'user_id');
```
## 4. Memory Analysis
- **Memory leaks**: Event listeners not cleaned up, intervals not cleared, subscriptions not unsubscribed
- **Large object retention**: Holding references to data no longer needed
- **Unbounded caches**: Caches that grow forever without eviction
- **String concatenation in loops**: Use array join or StringBuilder instead
- **Loading entire files into memory**: Stream large files instead
Flag pattern:
```
// ๐ด BAD โ memory leak: listener never removed
useEffect(() => {
window.addEventListener('resize', handleResize);
}, []);
// โ
GOOD โ cleanup on unmount
useEffect(() => {
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
```
## 5. Frontend Performance (if applicable)
- **Unnecessary re-renders**: Missing React.memo, useMemo, useCallback
- **Large bundle size**: Importing entire libraries when only one function is needed
- **Missing code splitting**: Large pages that should be lazy loaded
- **Unoptimized images**: Missing compression, wrong format, no lazy loading
- **Layout thrashing**: Reading and writing DOM properties in a loop
- **Missing virtualization**: Rendering thousands of list items instead of virtualizing
- **Blocking main thread**: Heavy computation not offloaded to Web Worker
Flag pattern:
```
// ๐ด BAD โ re-computes on every render
const sorted = items.sort((a, b) => a.name.localeCompare(b.name));
// โ
GOOD โ memoized
const sorted = useMemo(
() => [...items].sort((a, b) => a.name.localeCompare(b.name)),
[items]
);
```
## 6. API & Network Performance
- **Missing caching**: Responses that could be cached (HTTP headers, Redis, in-memory)
- **No request batching**: Multiple small requests that could be combined
- **Missing compression**: Large JSON responses without gzip/brotli
- **Synchronous operations**: Blocking calls that could be parallelized
- **No pagination**: Returning unbounded result sets
- **Missing timeouts**: External calls without timeout limits
Flag pattern:
```
// ๐ด BAD โ sequential when independent
const users = await fetchUsers();
const products = await fetchProducts();
const orders = await fetchOrders();
// โ
GOOD โ parallel execution
const [users, products, orders] = await Promise.all([
fetchUsers(),
fetchProducts(),
fetchOrders(),
]);
```
## 7. Concurrency & Async
- **Uncontrolled parallelism**: Firing 10,000 requests at once instead of batching
- **Missing debounce/throttle**: Search inputs firing on every keystroke
- **Blocking event loop**: CPU-heavy sync operations in Node.js
- **Missing queue**: Tasks that should be queued and processed in background
## 8. Build & Tooling (if applicable)
- Slow builds from unnecessary transpilation
- Missing tree shaking
- Duplicated dependencies in bundle
- Missing caching in CI/CD pipeline
## Output Format
For each issue found:
**[IMPACT] Category โ File:Line**
- **Problem**: What's slow and why
- **Current complexity**: O(?) or estimated impact
- **Suggested fix**: How to improve it
- **Expected improvement**: What performance gain to expect
```
// before (slow)
...
// after (fast)
...
```
Impact levels:
- ๐ด **HIGH** โ Causes noticeable slowdown or crashes at scale. Fix first.
- ๐ก **MEDIUM** โ Degrades performance under load. Fix soon.
- ๐ข **LOW** โ Minor inefficiency. Optimize when convenient.
## Summary
End every analysis with:
1. **Biggest bottleneck** โ The single highest-impact issue
2. **Quick wins** โ Changes that take <30 minutes and give noticeable improvement
3. **Estimated improvement** โ What overall performance gain to expect after fixes
4. **Measurement plan** โ How to verify the improvements (specific metrics to track, tools to use)
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.