mcpField
O
optimizing-performance

optimizing-performance

github.com/cloudai-x开发1.4k213 次安装4 周前更新
代码仓库

关于 optimizing-performance

为关注性能的开发者提供诊断与优化工作流,强调先测量基线、定位瓶颈,再验证优化效果和回归情况。

主要功能

  1. 01基线测量与性能分析
  2. 02瓶颈分类与定位
  3. 03前端、缓存和算法优化
  4. 04优化前后对比验证
  5. 05性能目标与检查清单

适用场景

  1. 01排查应用响应缓慢
  2. 02分析 CPU、内存或 I/O 瓶颈
  3. 03减少前端包体积和加载时间
  4. 04验证优化是否引入回归

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/cloudai-x/claude-workflow-v2 --skill optimizing-performance

安装后在 Claude Code 中输入/optimizing-performance确认已加载。

详细介绍

优化性能

何时加载
  • 触发条件:诊断速度缓慢、性能分析、缓存策略、缩短加载时间、优化包体积
  • 跳过:以正确性为重点且无需考虑性能的工作

性能优化工作流

复制此清单并跟踪进度:

Performance Optimization Progress:
- [ ] Step 1: Measure baseline performance
- [ ] Step 2: Identify bottlenecks
- [ ] Step 3: Apply targeted optimizations
- [ ] Step 4: Measure again and compare
- [ ] Step 5: Repeat if targets not met

关键规则:没有数据,绝不优化。更改前后都要进行性能分析。

第 1 步:测量基准

性能分析命令
# Node.js profiling
node --prof app.js
node --prof-process isolate*.log > profile.txt

# Python profiling
python -m cProfile -o profile.stats app.py
python -m pstats profile.stats

# Web performance
lighthouse https://example.com --output=json

第 2 步:识别瓶颈

常见瓶颈类别
类别症状工具
CPUCPU 使用率高、计算缓慢性能分析器、火焰图
内存RAM 占用高、GC 暂停、OOM堆快照、内存分析器
I/O磁盘/网络缓慢、等待strace、网络检查器
数据库查询缓慢、锁竞争查询分析器、EXPLAIN

第 3 步:应用优化

前端优化

包体积:

// ❌ Import entire library
import _ from "lodash";

// ✅ Import only needed functions
import debounce from "lodash/debounce";

// ✅ Use dynamic imports for code splitting
const HeavyComponent = lazy(() => import("./HeavyComponent"));

渲染:

// ❌ Render on every parent update
function Child({ data }) {
  return <ExpensiveComponent data={data} />;
}

// ✅ Memoize when props don't change
const Child = memo(function Child({ data }) {
  return <ExpensiveComponent data={data} />;
});

// ✅ Use useMemo for expensive computations
const processed = useMemo(() => expensiveCalc(data), [data]);

图像:


<img src="large-image.jpg" />


<img
  src="image.webp"
  srcset="image-300.webp 300w, image-600.webp 600w"
  sizes="(max-width: 600px) 300px, 600px"
  width="600"
  height="400"
  alt="Description"
  loading="lazy"
  decoding="async"
/>
后端优化

数据库查询:

-- ❌ N+1 Query Problem
SELECT * FROM users;
-- Then for each user:
SELECT * FROM orders WHERE user_id = ?;

-- ✅ Single query with JOIN
SELECT u.id, u.name, o.id AS order_id, o.total
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;

-- ✅ Or use pagination
SELECT id, name FROM users WHERE id > :last_id ORDER BY id LIMIT 100;

缓存策略:

// Multi-layer caching
const getUser = async (id) => {
  // L1: In-memory cache (fastest)
  let user = memoryCache.get(`user:${id}`);
  if (user) return user;

  // L2: Redis cache (fast)
  user = await redis.get(`user:${id}`);
  if (user) {
    user = JSON.parse(user);
    memoryCache.set(`user:${id}`, user, 60);
    return user;
  }

  // L3: Database (slow)
  user = await db.users.findById(id);
  await redis.setex(`user:${id}`, 3600, JSON.stringify(user));
  memoryCache.set(`user:${id}`, user, 60);

  return user;
};

异步处理:

// ❌ Blocking operation
app.post("/upload", async (req, res) => {
  await processVideo(req.file); // Takes 5 minutes
  res.send("Done");
});

// ✅ Queue for background processing
app.post("/upload", async (req, res) => {
  const jobId = await queue.add("processVideo", { file: req.file });
  res.status(202).send({ jobId, status: "processing" });
});
算法优化
// ❌ 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;
}

// ✅ O(n) - hash map
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 [...duplicates];
}

第 4 步:再次测量

应用优化后,重新进行性能分析并比较:

Comparison Checklist:
- [ ] Run same profiling tools as baseline
- [ ] Compare metrics before vs after
- [ ] Verify no regressions in other areas
- [ ] Document improvement percentages

性能目标

Web 指标
指标良好需要改进较差
LCP< 2.5s2.5-4s> 4s
INP< 200ms200-500ms> 500ms
CLS< 0.10.1-0.25> 0.25
TTFB< 800ms800ms-1.8s> 1.8s
API 性能
指标目标
P50 延迟< 100ms
P95 延迟< 500ms
P99 延迟< 1s
错误率< 0.1%

验证

优化后,验证结果:

Performance Validation:
- [ ] Metrics improved from baseline
- [ ] No functionality regressions
- [ ] No new errors introduced
- [ ] Changes are sustainable (not one-time fixes)
- [ ] Performance gains documented

如果未达到目标,请返回第 2 步,找出剩余的瓶颈。

评论

支持 Markdown