mcpField
P
performance-optimizer

performance-optimizer

github.com/sickn33开发49.3k165 次安装今天更新
代码仓库

关于 performance-optimizer

面向开发者的软件性能优化技能,指导测量运行表现、定位瓶颈、实施针对性改动并检查结果。涵盖前端、API、数据库和内存问题,同时强调正确性与环境验证。

主要功能

  1. 01改动前测量性能
  2. 02分析浏览器和 Node.js 工作负载
  3. 03检查数据库查询与执行计划
  4. 04处理常见前端和 API 瓶颈
  5. 05对比结果并验证正确性
  6. 06考虑工作负载与安全边界

适用场景

  1. 01排查页面加载或交互缓慢
  2. 02减少 API 或数据库操作耗时
  3. 03诊断内存使用过高
  4. 04以基线验证性能改动

安装

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

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill performance-optimizer

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

附带文件README.md

详细介绍

性能优化器

查找并修复性能瓶颈。测量、优化、验证。让它更快。

何时使用此技能

  • 应用运行缓慢或卡顿
  • 用户抱怨性能问题
  • 页面加载时间过长
  • API 响应缓慢
  • 数据库查询耗时过长
  • 用户提到“慢”“卡顿”“性能”或“优化”

优化流程

1. 先测量

没有测量,绝不优化:

// Measure execution time
console.time('operation');
await slowOperation();
console.timeEnd('operation'); // operation: 2341ms

测量内容:

  • 页面加载时间
  • API 响应时间
  • 数据库查询时间
  • 函数执行时间
  • 内存使用量
  • 网络请求
2. 找出瓶颈

使用性能分析工具找出耗时的部分:

浏览器:

DevTools → Performance tab → Record → Stop
Look for long tasks (red bars)

Node.js:

node --prof app.js
node --prof-process isolate-*.log > profile.txt

数据库:

EXPLAIN ANALYZE SELECT * FROM users WHERE email = '[email protected]';
3. 优化

优先修复最慢的部分(影响最大)。

常见优化

数据库查询

问题:N+1 查询

// Bad: N+1 queries
const users = await db.users.find();
for (const user of users) {
  user.posts = await db.posts.find({ userId: user.id }); // N queries
}

// Alternative: batched population; inspect actual generated queries
const users = await db.users.find()
  .populate('posts'); // May issue additional batched queries; not necessarily a JOIN

问题:缺少索引

-- Check slow query
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
-- A sequential scan may be optimal for small tables/low-selectivity queries.

-- Add index
CREATE INDEX idx_users_email ON users(email);

-- Check again
EXPLAIN SELECT * FROM users WHERE email = '[email protected]';
-- Compare actual cost/latency and write/storage impact.

**问题:SELECT ***

// Bad: Fetches all columns
const users = await db.query('SELECT * FROM users');

// Good: Only needed columns
const users = await db.query('SELECT id, name, email FROM users');

问题:没有分页

// Bad: Returns all records
const users = await db.users.find();

// Good: Paginated
const users = await db.users.find()
  .limit(20)
  .skip((page - 1) * 20);
API 性能

问题:没有缓存

// Bad: Hits database every time
app.get('/api/stats', async (req, res) => {
  const stats = await db.stats.calculate(); // Slow
  res.json(stats);
});

// Good: Cache for 5 minutes
const cache = new Map();
app.get('/api/stats', async (req, res) => {
  const cached = cache.get('stats');
  if (cached && Date.now() - cached.time < 300000) {
    return res.json(cached.data);
  }
  
  const stats = await db.stats.calculate();
  cache.set('stats', { data: stats, time: Date.now() });
  res.json(stats);
});

问题:顺序执行操作

// Bad: Sequential (slow)
const user = await getUser(id);
const posts = await getPosts(id);
const comments = await getComments(id);
// Total: 300ms + 200ms + 150ms = 650ms

// Good: Parallel (fast)
const [user, posts, comments] = await Promise.all([
  getUser(id),
  getPosts(id),
  getComments(id)
]);
// Total: max(300ms, 200ms, 150ms) = 300ms

问题:负载过大

// Bad: Returns everything
res.json(users); // 5MB response

// Good: Only needed fields
res.json(users.map(u => ({
  id: u.id,
  name: u.name,
  email: u.email
}))); // 500KB response
前端性能

问题:不必要的重新渲染

// Bad: Re-renders on every parent update
function UserList({ users }) {
  return users.map(user => <UserCard user={user} />);
}

// Good: Memoized
const UserCard = React.memo(({ user }) => {
  return <div>{user.name}</div>;
});

问题:Bundle 过大

// Bad: Imports entire library
import _ from 'lodash'; // 70KB

// Good: Import only what you need
import debounce from 'lodash/debounce'; // 2KB

问题:没有代码拆分

// Bad: Everything in one bundle
import HeavyComponent from './HeavyComponent';

// Good: Lazy load
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));

问题:图像未优化


<img src="photo.jpg" /> 


<img 
  src="photo-small.webp" 
  srcset="photo-small.webp 400w, photo-large.webp 800w"
  loading="lazy"
  width="400"
  height="300"
/> 
算法优化

问题:算法效率低

// Bad: 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;
}

// Good: O(n) - single pass with Set
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 Array.from(duplicates);
}

问题:重复计算

// Bad: Calculates every time
function getTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
// Called 100 times in render

// Good: Memoized
const getTotal = useMemo(() => {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}, [items]);
内存优化

问题:内存泄漏

// Bad: Event listener not cleaned up
useEffect(() => {
  window.addEventListener('scroll', handleScroll);
  // Memory leak!
}, []);

// Good: Cleanup
useEffect(() => {
  window.addEventListener('scroll', handleScroll);
  return () => window.removeEventListener('scroll', handleScroll);
}, []);

问题:内存中的数据过多

// Bad: Loads entire file into memory
const data = fs.readFileSync('huge-file.txt'); // 1GB

// Good: Stream it
const stream = fs.createReadStream('huge-file.txt');
stream.on('data', chunk => process(chunk));

正确性与基准测试边界

两个 findDuplicates 示例的输出语义不同:嵌套循环会为每一对匹配项重复输出一个项目,而 Set 版本只会输出每个重复值一次(且对 NaN 的相等性判断不同)。更改算法前,先明确所需的契约。统计信息缓存只适用于共享的公开数据;特定用户或租户的结果需要经过授权的键和失效机制。流式处理必须处理错误、背压和异步处理。EXPLAIN ANALYZE 会执行查询;使用前请确认目标和负载。以下所有时间和大小仅为示例,并非实测结果:应在具有代表性的工作负载下重复运行并进行比较,同时参考环境和样本统计信息,并进行回归检查。

衡量影响

始终测量优化前后的数据:

// Before optimization
console.time('query');
const users = await db.users.find();
console.timeEnd('query');
// query: 2341ms

// After optimization (added index)
console.time('query');
const users = await db.users.find();
console.timeEnd('query');
// query: 23ms

// Improvement: 100x faster!

性能预算

设定目标:

Page Load: < 2 seconds
API Response: < 200ms
Database Query: < 50ms
Bundle Size: < 200KB
Time to Interactive: < 3 seconds

工具

浏览器:

  • Chrome DevTools 的 Performance 选项卡
  • Lighthouse(审计)
  • Network 选项卡(瀑布图)

Node.js:

  • node --prof(性能分析)
  • clinic(诊断)
  • autocannon(负载测试)

数据库:

  • EXPLAIN ANALYZE(查询计划)
  • 慢查询日志
  • 数据库性能分析器

监控:

  • New Relic
  • Datadog
  • Sentry Performance

快速优化

简单易行、效果显著的优化:

  1. 在经常查询的列上添加数据库索引
  2. 在服务端启用 gzip 压缩
  3. 为耗时操作添加缓存
  4. 延迟加载图像和大型组件
  5. 对静态资源使用 CDN
  6. 缩小并压缩 JavaScript/CSS
  7. 移除未使用的依赖项
  8. 使用分页,而非一次加载所有数据
  9. 优化图像(WebP、适当的尺寸)
  10. 在服务端启用 HTTP/2

优化检查清单

  • 已测量当前性能
  • 已确定瓶颈
  • 已应用优化
  • 已测量改进效果
  • 已验证功能仍可正常使用
  • 未引入新问题
  • 已记录更改

何时不应优化

  • 过早优化(实际变慢时再优化)
  • 微优化(页面耗时 5 秒时,只节省 1 毫秒)
  • 可读性比微小的速度提升更重要
  • 性能已经足够快时

核心原则

  • 优化前先测量
  • 优先修复影响最大的瓶颈
  • 优化后再次测量,证明效果
  • 不要为了微小的提升牺牲可读性
  • 在接近生产环境的环境中进行性能分析
  • 考虑 80/20 法则(20% 的代码导致 80% 的性能问题)

相关技能

  • @database-design - 查询优化
  • @codebase-audit-pre-push - 代码审查
  • @bug-hunter - 调试

限制

  • 仅当任务明显符合上述描述的范围时,才使用此技能。
  • 不要将输出视为对特定环境的验证、测试或专家审查的替代。
  • 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。

评论

支持 Markdown