agentleFS
nisarthnisarth/claude-skills-store/skills/engineering/performance-optimization/SKILL.md

performance-optimization

Skill1 starsChanged 7 months agoMITView on GitHub

Profile and optimize code performance. Identify bottlenecks, memory leaks, N+1 queries, slow renders, and inefficient algorithms. Benchmark before and after changes. Trigger with "this is slow", "optimize performance", "find the bottleneck", "profile this code", "memory leak", "N+1 query", "slow render", or when the user reports latency, high CPU, or memory issues.

125 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use constraint-driven-development, git-workflow-and-versioning and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • MrCipherSmithSkill

    constraint-driven-development

    Use when a project needs a persistent, measurable quality bar — starting a project without documented standards, 'set up constraints', or when coverage/perf/a11y thresholds get re-debated per-PR. Produces CONSTRAINTS.md with enforceable numbers, ratchets, and a guard against silent weakening. NOT for throwaway prototypes or a one-off CI setup.

    Also in 15 projects that use this

  • LLl0k0laDSkill

    git-workflow-and-versioning

    Use when making any code change. Use when committing, branching, resolving conflicts, or when you need to organize work across multiple parallel streams.

    Also in 42 projects that use this

  • LLl0k0laDSkill

    using-agent-skills

    Use when starting a session or when you need to discover which skill applies to the current task. This is the meta-skill that governs how all other skills are discovered and invoked.

    Also in 33 projects that use this

  • HK-hubSkill

    deprecation-and-migration

    Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when deciding whether to maintain or sunset existing code.

    Also in 39 projects that use this

  • ukanwatSkill

    input-systems

    Architect game input — action mapping (abstracting keys into named actions), rebinding with conflict detection and persistence, multi-device support (keyboard, gamepad, touch), analog deadzones, and feel features like input buffering and coyote time, plus accessibility. Engine-neutral. Use when the user mentions input mapping, rebind controls, gamepad support, deadzone, input buffering, coyote time, or accessible controls.

    Also in 4 projects that use this

  • HK-hubSkill

    observability-and-instrumentation

    Instruments code so production behavior is visible and diagnosable. Use when adding logging, metrics, tracing, or alerting. Use when shipping any feature that runs in production and you need evidence it works. Use when production issues are reported but you can't tell what happened from the available data.

    Also in 31 projects that use this

  • +6 more from LLl0k0laD

The file

Show its rules and text

We split this skill into the rules it gives an agent

25 rules. 0 are common, 17 are distinctive, and 8 are very specific to this project.

  • 0

    Common

    Most of the 110 edited versions we read keep these.

  • 17

    Distinctive

    This author's own choices. Worth a look.

  • 8

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Before optimizing anything, measure the current state:

    line 33
  2. Very specific:

    Backend latency: Check logs, APM data, or run time curl -s <endpoint> for quick measurement.

    line 35
  3. Distinctive:

    Frontend rendering: Check for layout thrashing, excessive re-renders, or large bundle sizes.

    line 37
  4. Very specific:

    Memory usage: Check process memory with ps aux | grep <process> or language-specific profilers.

    line 38
  5. Very specific:

    CPU usage: Check with top, htop, or application profilers.

    line 39
  6. Very specific:

    N+1 queries: Look for queries inside loops.

    line 57
  7. Very specific:

    Missing indexes: Run EXPLAIN ANALYZE on slow queries.

    line 58
  8. Very specific:

    Over-fetching: Check for SELECT * when only a few columns are needed.

    line 59
  9. Very specific:

    Missing pagination: Look for unbounded queries without LIMIT.

    line 60
  10. Distinctive:

    Connection pool exhaustion: Check pool size vs. concurrent request count.

    line 61
  11. Distinctive:

    Algorithmic complexity: Look for O(n^2) or worse in hot paths (nested loops over collections).

    line 64
  12. Distinctive:

    Missing connection reuse: Not using HTTP keep-alive or connection pooling.

    line 81
  13. Very specific:

    Use will-change CSS property sparingly for known animation targets.

    line 112
  14. Distinctive:

    Use binary search on sorted data instead of linear scan.

    line 117
  15. Distinctive:

    Use streaming/chunked processing for large datasets instead of loading all into memory.

    line 119
  16. Distinctive:

    Run the full test suite after optimization changes.

    line 136
  17. Distinctive:

    Check that behavior is identical (same outputs for same inputs).

    line 137
  18. Distinctive:

    Action: Read the endpoint handler, trace database queries, identify N+1 patterns or missing indexes, suggest eager loading and index …

    line 178
  19. Distinctive:

    Action: Check for virtualization, look at component re-render patterns, check bundle size, suggest React.memo, virtualization, and …

    line 181
  20. Distinctive:

    Action: Look for event listener leaks, growing caches without eviction, unclosed database connections, circular references preventing …

    line 184
  21. Distinctive:

    Always measure before optimizing.

    line 191
  22. Distinctive:

    Avoid premature optimization.

    line 194
  23. Distinctive:

    Document why an optimization was made, not just what.

    line 195
  24. Distinctive:

    Test with realistic data volumes.

    line 197
  25. Distinctive:

    Consider the 80/20 rule: 80% of performance issues come from 20% of the code.

    line 198

“Common” is measured: kept by at least 6 in 10 of the 110 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Performance Optimization

Profile, diagnose, and fix performance bottlenecks. Covers CPU profiling, memory analysis, database query optimization, frontend rendering, bundle size reduction, and algorithmic improvements. Always benchmark before and after.

Workflow

Step 1: Establish Baseline

Before optimizing anything, measure the current state:

  • Backend latency: Check logs, APM data, or run time curl -s <endpoint> for quick measurement.
  • Database queries: Enable query logging or use EXPLAIN ANALYZE on suspect queries.
  • Frontend rendering: Check for layout thrashing, excessive re-renders, or large bundle sizes.
  • Memory usage: Check process memory with ps aux | grep <process> or language-specific profilers.
  • CPU usage: Check with top, htop, or application profilers.

Record baseline metrics:

| Metric              | Current Value | Target Value |
|---------------------|---------------|--------------|
| Response time (p50) | <value>       | <target>     |
| Response time (p99) | <value>       | <target>     |
| Memory usage        | <value>       | <target>     |
| Bundle size         | <value>       | <target>     |
| Query count         | <value>       | <target>     |

Step 2: Identify Bottlenecks

Systematically check each performance layer:

Database (most common bottleneck):

  • N+1 queries: Look for queries inside loops. Search for ORM calls (.find(), .get(), .load()) inside iteration blocks.
  • Missing indexes: Run EXPLAIN ANALYZE on slow queries. Look for sequential scans on large tables.
  • Over-fetching: Check for SELECT * when only a few columns are needed.
  • Missing pagination: Look for unbounded queries without LIMIT.
  • Connection pool exhaustion: Check pool size vs. concurrent request count.

Backend code:

  • Algorithmic complexity: Look for O(n^2) or worse in hot paths (nested loops over collections).
  • Synchronous I/O: Blocking calls in async contexts (file reads, HTTP calls without await).
  • Unnecessary serialization: Repeated JSON.parse/stringify, excessive object cloning.
  • Missing caching: Repeated expensive computations or API calls with same inputs.
  • Memory leaks: Growing arrays, unclosed connections, event listener accumulation.

Frontend rendering:

  • Excessive re-renders: Components re-rendering on every state change (React: missing useMemo, useCallback, React.memo).
  • Layout thrashing: Reading then writing DOM properties in a loop (forces synchronous reflow).
  • Large bundles: Importing entire libraries when only one function is needed.
  • Unoptimized images: Large images without lazy loading, missing srcset, uncompressed formats.
  • Blocking resources: Render-blocking CSS/JS in the critical path.

I/O and Network:

  • Sequential API calls: Requests that could be parallelized with Promise.all().
  • Missing compression: Response bodies not gzipped/brotli compressed.
  • Chatty protocols: Many small requests instead of batched operations.
  • Missing connection reuse: Not using HTTP keep-alive or connection pooling.

Step 3: Apply Fixes

For each identified bottleneck, apply the appropriate fix:

Database fixes:

-- Add index for slow query
CREATE INDEX CONCURRENTLY idx_orders_user_created
ON orders (user_id, created_at DESC);

-- Replace N+1 with eager loading (ORM example)
-- Before: users.map(u => u.getPosts())  -- N+1
-- After:  User.findAll({ include: [Post] })  -- 1 query with JOIN

-- Add pagination
SELECT * FROM orders WHERE user_id = $1
ORDER BY created_at DESC LIMIT 20 OFFSET 0;

Caching strategies:

  • In-memory cache: For frequently accessed, rarely changing data (config, feature flags).
  • Redis/Memcached: For shared cache across instances (session data, API responses).
  • HTTP caching: Set Cache-Control, ETag, Last-Modified headers for static and semi-static responses.
  • Memoization: Cache pure function results keyed by arguments.

Frontend fixes:

  • Code-split routes with dynamic imports: React.lazy(() => import('./Page')).
  • Virtualize long lists with react-window or @tanstack/virtual.
  • Debounce expensive event handlers (search, resize, scroll).
  • Use will-change CSS property sparingly for known animation targets.
  • Preload critical resources: <link rel="preload" href="font.woff2" as="font">.

Algorithmic fixes:

  • Replace array lookups with Set/Map for O(1) access.
  • Use binary search on sorted data instead of linear scan.
  • Replace recursive solutions with iterative ones to avoid stack overflow.
  • Use streaming/chunked processing for large datasets instead of loading all into memory.

Step 4: Benchmark After Changes

Re-measure with the same methodology as Step 1:

| Metric              | Before  | After   | Improvement |
|---------------------|---------|---------|-------------|
| Response time (p50) | 450ms   | 120ms   | 73% faster  |
| Response time (p99) | 2100ms  | 380ms   | 82% faster  |
| Memory usage        | 512MB   | 340MB   | 34% less    |
| Bundle size         | 1.2MB   | 680KB   | 43% smaller |
| Query count         | 47/req  | 5/req   | 89% fewer   |

Verify no regressions:

  • Run the full test suite after optimization changes.
  • Check that behavior is identical (same outputs for same inputs).
  • Load test under realistic concurrency to verify improvements hold.

Output Format

## Performance Analysis

### Baseline Metrics
<table of current measurements>

### Bottlenecks Identified

#### [P1] <Issue> — <location>
**Impact**: <quantified impact on latency/memory/CPU>
**Root Cause**: <why this is slow>
**Fix**:
```<language>
// before
<slow code>

// after
<optimized code>

Expected Improvement: <estimated gain>

Optimization Plan (priority order)

  1. <highest impact, lowest effort fix>
  2. <next priority>
  3. <next priority>

After Optimization

<table comparing before/after metrics>

Remaining Opportunities

  • <future optimization ideas that were out of scope>

## Examples

**User**: "This API endpoint takes 3 seconds to respond"
**Action**: Read the endpoint handler, trace database queries, identify N+1 patterns or missing indexes, suggest eager loading and index additions, benchmark before/after.

**User**: "Our React app is sluggish when scrolling the list page"
**Action**: Check for virtualization, look at component re-render patterns, check bundle size, suggest React.memo, virtualization, and code-splitting.

**User**: "Memory keeps growing until the service crashes"
**Action**: Look for event listener leaks, growing caches without eviction, unclosed database connections, circular references preventing garbage collection.

**User**: "Profile this function for performance"
**Action**: Analyze the algorithm complexity, look for unnecessary allocations, check I/O patterns, suggest optimizations with benchmarks.

## Best Practices

- Always measure before optimizing. Intuition about bottlenecks is often wrong.
- Optimize the highest-impact bottleneck first. A 10x improvement on a function called once matters less than a 2x improvement on one called 10,000 times.
- Profile in production-like conditions. Development environments hide real performance issues.
- Avoid premature optimization. If it is fast enough, do not add complexity to make it faster.
- Document why an optimization was made, not just what. Future developers may simplify away your optimization not knowing it was intentional.
- Cache invalidation is harder than caching. Always design the invalidation strategy first.
- Test with realistic data volumes. An O(n^2) algorithm is fine for 100 items but breaks at 100,000.
- Consider the 80/20 rule: 80% of performance issues come from 20% of the code.
- Set performance budgets and alert when they are exceeded rather than only reacting to complaints.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.