mode-optimize

v2026.09.24

Optimize mode for refactoring, performance improvement, and code cleanup. Use when user requests optimization or identifies slow code. Measures baseline, identifies bottlenecks, improves without changing behavior, compares before/after.

GitHub
安装命令
npx skhub add duck4nh/mode-optimize
Markdown
SKILL.md

Optimize Mode

Goal: Improve quality WITHOUT changing behavior.

Process

  1. Risk assessment (classify change type)
  2. Measure current state (baseline)
  3. Identify main bottleneck
  4. Choose safe optimization strategy
  5. Propose improvements + predict results
  6. Refactor by priority order
  7. Compare before/after
  8. Ensure tests still pass
  9. Document rollback plan

Performance Metrics by Language

LanguageBuild/SizeRuntimeProfiling Tool
JS/TSBundle < 500KBRender < 16msWebpack Analyzer, Lighthouse
PythonN/AResponse < 100mscProfile, py-spy
JavaJAR sizeGC pause < 50msJProfiler, VisualVM
GoBinary sizep99 latencypprof, go test -bench

Common Optimization Patterns

All Languages

IssueSolutionImpact
Slow DB queriesAdd indexes, limit results, eager loadingHigh
N+1 queriesBatch loading, JOINsHigh
Large payloadsPagination, compression, lazy loadingHigh
Repeated calculationsCaching, memoizationMedium
Memory leaksProper cleanup, weak referencesMedium

Language-Specific

LanguageCommon IssueSolution
JS/TSUnnecessary re-rendersReact.memo, useMemo, useCallback
JS/TSLarge bundleCode splitting, tree shaking, dynamic imports
PythonSlow loopsNumPy vectorization, list comprehensions
GoExcessive allocationsSync.Pool, pre-allocate slices

Output Format

## OPTIMIZE

**Issue:** [slow / duplicate code / hard to maintain]
**Language:** [JS/Python/Java/Go/PHP/Ruby]

**Baseline:**
- Response time: X ms
- Memory: X MB
- LOC: X

---

### Bottleneck:
| Issue | Location | Severity |
|-------|----------|----------|
| [Description] | `file:line` | High |

### Proposal:
| Item | Before | After | Change |
|------|--------|-------|--------|
| Response time | 500ms | 50ms | -90% |
| Memory | 200MB | 50MB | -75% |

### Regression Check:
- [ ] Tests still pass
- [ ] Behavior unchanged
- [ ] Performance verified

## Risk Assessment

### Risk Classification
| Change Type      | Risk Level | Rollback Ease | Strategy                        |
| ---------------- | ---------- | ------------- | ------------------------------- |
| Algorithm change | High       | Easy          | A/B test, gradual rollout       |
| Database schema  | High       | Hard          | Migration plan, rollback script |
| Caching layer    | Medium     | Medium        | Feature flag, monitor           |
| Code refactor    | Low        | Easy          | Tests, revert if fail           |

### Risk Questions
- [ ] What if optimization introduces bugs?
- [ ] Can we rollback easily?
- [ ] What's the blast radius?
- [ ] Who gets affected if fails?

### Safe Optimization Strategies

#### Strategy 1: Feature Flag (Recommended for critical paths)
```typescript
// Use feature flag for new optimized code
const useNewOptimization = featureFlags.get('use-v2-algorithm', false);

if (useNewOptimization) {
  return optimizedMethod(data);
} else {
  return legacyMethod(data);
}

Strategy 2: Gradual Rollout

**Week 1:** 5% of traffic
**Week 2:** 25% of traffic
**Week 3:** 50% of traffic
**Week 4:** 100% of traffic

**Monitor after each phase:**
- Error rate
- Performance metrics
- User complaints

Strategy 3: A/B Testing

**Control:** Current implementation
**Variant:** Optimized implementation

**Metrics to compare:**
- Response time (p50, p95, p99)
- Error rate
- Resource usage
- User satisfaction

**Statistical significance:** 95% confidence

Rollback Plan

Document Before Optimizing

**Rollback Trigger:**
- Error rate increases > 5%
- p95 latency degrades > 20%
- User complaints > X/hour

**Rollback Steps:**
1. [Revert commit / disable feature flag]
2. [Verify old behavior restored]
3. [Monitor for Y minutes]
4. [Document lessons learned]

Optimization Safety Checklist

  • Baseline metrics documented
  • Rollback plan written
  • Feature flag available (if critical)
  • Monitoring/alerts configured
  • Tests covering the change
  • Code reviewed
  • Staged rollout planned

## Quick Optimization Examples

### React Re-render
```diff
- function UserList({ users }) {
-   return users.map(u => <UserCard user={u} />);
- }
+ const UserList = React.memo(function UserList({ users }) {
+   return users.map(u => <UserCard key={u.id} user={u} />);
+ });

Python N+1 Query

- for order in orders:
-     print(order.customer.name)
+ orders = Order.objects.select_related('customer').all()
+ for order in orders:
+     print(order.customer.name)

Go Slice Pre-allocation

- var results []Result
- for _, item := range items {
-     results = append(results, process(item))
- }
+ results := make([]Result, 0, len(items))
+ for _, item := range items {
+     results = append(results, process(item))
+ }

Principles

DON'TDO
Optimize prematurelyMeasure first, optimize later
Change behaviorKeep behavior unchanged
Prioritize clevernessReadability > Performance
Skip testsRe-run tests after changes
Optimize everythingFocus on bottlenecks (80/20 rule)
发现
标签

此技能尚未发布标签。

版本
最新版本元数据

版本

v2026.09.24

发布时间

Sep 24, 2026

分类

未分类

许可证

未指定

源路径

templates/.opencode/skill/mode-optimize

默认分支

main

最新提交

90de2ac

Tree SHA

0df3a5c