feat: improved the Claude Kit as a plugin

This commit is contained in:
duthaho
2026-04-19 14:09:14 +07:00
parent 3103a8da1b
commit d1a6d2a2bc
186 changed files with 771 additions and 1691 deletions
+116
View File
@@ -0,0 +1,116 @@
---
name: performance-optimization
argument-hint: "[file or function]"
description: >
Use when analyzing or optimizing code performance — including profiling, benchmarking, fixing N+1 queries, reducing bundle size, eliminating memory leaks, or improving algorithm complexity. Trigger for keywords like "slow", "performance", "optimize", "profiling", "memory leak", "bundle size", "N+1", "re-render", "benchmark", "latency", "throughput", or any request to make code faster. Also activate when investigating production performance issues or when code review flags performance concerns.
---
# Performance Optimization
## When to Use
- Profiling slow code to find bottlenecks
- Fixing N+1 query problems
- Reducing JavaScript bundle size
- Eliminating memory leaks
- Improving algorithm complexity
- Benchmarking before/after optimization
- Investigating production latency issues
## When NOT to Use
- Premature optimization — profile first, optimize second
- Caching strategy design — use `caching`
- Database schema/index design — use `databases`
- Code structure improvement — use `refactoring`
---
## Quick Reference
| Topic | Reference | Key content |
|-------|-----------|-------------|
| Profiling tools | `references/profiling.md` | Python (cProfile, py-spy, Scalene) and JS/TS (DevTools, Lighthouse, clinic.js) |
| Anti-patterns | `references/anti-patterns.md` | N+1 queries, unnecessary re-renders, event loop blocking, memory leaks |
---
## Optimization Workflow
1. **Measure first** — profile to find the actual bottleneck
2. **Set a target** — "reduce p95 latency from 500ms to 100ms"
3. **Optimize the hot path** — fix the #1 bottleneck, not everything
4. **Benchmark before/after** — prove the improvement with numbers
5. **Check for regressions** — ensure correctness wasn't sacrificed
---
## Profiling Quick Start
### Python
```bash
# CPU profiling
python -m cProfile -o output.prof script.py
# Visualize: pip install snakeviz && snakeviz output.prof
# Live profiling (attach to running process)
py-spy top --pid 12345
# Line-by-line profiling
kernprof -lv script.py # requires @profile decorator
```
### JavaScript/TypeScript
```bash
# Bundle analysis
npx webpack-bundle-analyzer stats.json
# or: ANALYZE=true next build
# Node.js profiling
node --prof app.js
clinic doctor -- node app.js
# Benchmarking
npx vitest bench
```
---
## Common Anti-Patterns
| Anti-Pattern | Detection | Fix |
|-------------|-----------|-----|
| N+1 queries | `django-debug-toolbar`, `prisma.$on('query')` | `select_related`/`joinedload`/`include` |
| Unnecessary re-renders | React DevTools Profiler | `useMemo`, `useCallback`, `React.memo` |
| Blocking event loop | `clinic doctor`, high event loop lag | `worker_threads`, async variants |
| Memory leaks | Heap snapshots, growing `process.memoryUsage()` | Remove listeners, clear refs, bound caches |
| Unbounded lists | No pagination, full table scans | Cursor pagination, `LIMIT` |
| Heavy imports | Bundle analyzer showing large deps | Tree-shaking, `import { x }`, code splitting |
---
## Best Practices
1. **Profile before optimizing** — intuition about bottlenecks is often wrong.
2. **Optimize the hot path** — 80% of time is spent in 20% of code.
3. **Measure, don't guess** — use benchmarks with statistical significance.
4. **Set clear targets** — "faster" is not measurable; "p95 < 100ms" is.
5. **Avoid premature optimization** — correctness and readability come first.
## Common Pitfalls
1. **Optimizing cold paths** — spending time on code that runs once.
2. **Micro-benchmarking without context** — 10ns vs 20ns doesn't matter if the DB call takes 50ms.
3. **Sacrificing readability** — an unreadable optimization is a future bug.
4. **Caching without invalidation** — stale data is worse than slow data.
5. **Ignoring algorithmic complexity** — no amount of micro-optimization fixes O(n^2) on large inputs.
---
## Related Skills
- `caching` — Caching strategies (memoization, HTTP, Redis, CDN)
- `databases` — Query optimization, indexing, connection pooling
- `frontend` — React rendering optimization patterns
@@ -0,0 +1,115 @@
# Performance Anti-Patterns
## N+1 Queries
**Signal**: Many small queries instead of one batch query.
### SQLAlchemy (Python)
```python
# BAD: N+1 — each user triggers a query for posts
users = session.query(User).all()
for user in users:
print(user.posts) # lazy load, 1 query per user
# GOOD: eager loading
from sqlalchemy.orm import joinedload, selectinload
users = session.query(User).options(selectinload(User.posts)).all()
```
### Prisma (TypeScript)
```typescript
// BAD: N+1
const users = await prisma.user.findMany();
for (const user of users) {
const posts = await prisma.post.findMany({ where: { authorId: user.id } });
}
// GOOD: include
const users = await prisma.user.findMany({ include: { posts: true } });
```
### Django
```python
# BAD
for order in Order.objects.all():
print(order.customer.name) # N+1
# GOOD
for order in Order.objects.select_related('customer').all():
print(order.customer.name) # 1 query with JOIN
```
## Unnecessary Re-renders (React)
**Signal**: Components re-rendering when their data hasn't changed.
```typescript
// BAD: new object created every render
<Child style={{ color: 'red' }} />
// GOOD: stable reference
const style = useMemo(() => ({ color: 'red' }), []);
<Child style={style} />
// BAD: new function every render
<Button onClick={() => handleClick(id)} />
// GOOD: stable callback
const handleClick = useCallback(() => doSomething(id), [id]);
<Button onClick={handleClick} />
```
Detect with: React DevTools Profiler → "Highlight updates when components render"
## Blocking the Event Loop (Node.js)
**Signal**: High event loop lag, slow response times.
```typescript
// BAD: synchronous file read blocks everything
const data = fs.readFileSync('large-file.json');
// GOOD: async
const data = await fs.promises.readFile('large-file.json');
// BAD: CPU-heavy in main thread
const hash = crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512');
// GOOD: async or worker_threads
const hash = await new Promise((resolve, reject) => {
crypto.pbkdf2(password, salt, 100000, 64, 'sha512', (err, key) => {
err ? reject(err) : resolve(key);
});
});
```
## Memory Leaks
### Python
- Circular references with `__del__`
- Unclosed file handles / DB connections
- Growing global caches without TTL
- Detect: `objgraph`, `tracemalloc`
### JavaScript
- Detached DOM nodes
- Forgotten event listeners (`addEventListener` without `removeEventListener`)
- Closures capturing large scopes
- Unbounded `Map`/`Set` growth
- Detect: Chrome Heap Snapshots, `process.memoryUsage()`
## Heavy Imports / Bundle Bloat
```typescript
// BAD: imports entire library
import _ from 'lodash';
// GOOD: tree-shakeable import
import { debounce } from 'lodash-es';
// GOOD: native alternative
const debounce = (fn, ms) => { /* 5 lines */ };
```
Replace heavy deps: moment → dayjs, lodash → lodash-es or native, date-fns (tree-shakeable).
Use `React.lazy()` + `Suspense` for route-based code splitting.
@@ -0,0 +1,109 @@
# Profiling Tools Reference
## Python
### cProfile (built-in, function-level)
```bash
python -m cProfile -o output.prof script.py
# Visualize
pip install snakeviz && snakeviz output.prof
```
### py-spy (sampling, production-safe)
```bash
# Top-like view of running process
py-spy top --pid 12345
# Generate flame graph
py-spy record -o profile.svg --pid 12345
```
### line_profiler (line-by-line)
```bash
# Add @profile decorator to target function
kernprof -lv script.py
```
### memory_profiler (memory usage)
```bash
# Add @profile decorator
python -m memory_profiler script.py
# Or use stdlib tracemalloc for snapshot comparison
```
### Scalene (CPU + memory + GPU)
```bash
scalene script.py
# Modern alternative, AI-suggested optimizations
```
## JavaScript / TypeScript
### Chrome DevTools Performance
- Performance tab → Record → interact → Stop
- Flame chart shows main thread activity
- Look for long tasks (>50ms), layout thrashing
### Lighthouse (web vitals)
```bash
npx lighthouse https://localhost:3000 --output=json
# CI integration
npx @lhci/cli autorun
```
### Bundle Analysis
```bash
# Webpack
npx webpack-bundle-analyzer stats.json
# Next.js
ANALYZE=true next build
# Source map explorer
npx source-map-explorer dist/**/*.js
```
### clinic.js (Node.js)
```bash
# Event loop health
clinic doctor -- node app.js
# CPU flame graph
clinic flame -- node app.js
# Async bottlenecks
clinic bubbleprof -- node app.js
```
### Node.js built-in
```bash
node --prof app.js
node --prof-process isolate-*.log > profile.txt
```
## Benchmarking
### Python
```bash
# pytest-benchmark
pytest --benchmark-only
# timeit
python -m timeit -s "setup" "expression"
```
### JavaScript/TypeScript
```typescript
// Vitest bench (built-in)
// my-func.bench.ts
import { bench } from 'vitest';
bench('my function', () => {
myFunction(testData);
});
```
```bash
npx vitest bench
```