
关于
识别和修复代码、数据库和 API 中的性能瓶颈。通过前后对比测量证明改进效果。
name: performance-optimizer description: "识别并修复代码、数据库和 API 中的性能瓶颈。通过前后对比测量来证明改进效果。" category: development risk: safe source: community date_added: "2026-03-05"
性能优化器
发现并修复性能瓶颈。测量、优化、验证。让它变快。
何时使用此技能
- 应用运行缓慢或卡顿
- 用户抱怨性能问题
- 页面加载时间过长
- 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 = 'test@example.com';
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
}
// Good: Single query with JOIN
const users = await db.users.find()
.populate('posts'); // 1 query
问题:缺少索引
-- Check slow query
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
-- Shows: Seq Scan (bad)
-- Add index
CREATE INDEX idx_users_email ON users(email);
-- Check again
EXPLAIN SELECT * FROM users WHERE email = 'test@example.com';
-- Shows: Index Scan (good)
**问题: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>;
});
问题:包体积过大
// 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'));
问题:未优化的图片
<!-- Bad: Large image -->
<img src="photo.jpg" /> <!-- 5MB -->
<!-- Good: Optimized and responsive -->
<img
src="photo-small.webp"
srcset="photo-small.webp 400w, photo-large.webp 800w"
loading="lazy"
width="400"
height="300"
/> <!-- 50KB -->
算法优化
问题:低效算法
// Bad: O(n^2) - 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) - hash set
function findDuplicates(arr) {
const seen = new Set();
const duplicates = new Set();
for (const item of arr) {
if (seen.has(item)) duplicates.add(item);
else seen.add(item);
}
return [...duplicates];
}
兼容工具
Claude CodeCursor
标签
通用