专业的性能分析技能,能够识别代码性能瓶颈、评估运行效率并提供优化建议。
Analyzes code for performance bottlenecks including algorithmic complexity, resource usage, and database inefficiencies. It is triggered when reviewing code or investigating slow execution, providing specific optimization strategies and refactoring examples.
/plugin marketplace add Protagonistss/claude-plugins/plugin install code-review@claude-plugins-protagonisthsThis skill inherits all available tools. When active, it can use any tool Claude has access to.
专业的性能分析技能,能够识别代码性能瓶颈、评估运行效率并提供优化建议。
Performance Review 技能提供深度的代码性能分析能力,包括算法复杂度分析、资源使用评估、并发性能检查和数据库查询优化。
// 性能问题代码
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)
function findDuplicatesOptimized(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 Array.from(duplicates);
}
// 性能问题代码
function updateList(items) {
const list = document.getElementById('list');
list.innerHTML = ''; // 清空列表
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
list.appendChild(li); // 频繁DOM操作
});
}
// 优化方案
function updateListOptimized(items) {
const list = document.getElementById('list');
const fragment = document.createDocumentFragment();
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
fragment.appendChild(li);
});
list.innerHTML = '';
list.appendChild(fragment); // 一次性DOM操作
}
// 性能问题代码 - N+1查询问题
async function getUsersWithPosts() {
const users = await db.query('SELECT * FROM users');
for (const user of users) {
user.posts = await db.query(
'SELECT * FROM posts WHERE user_id = ?',
[user.id]
);
}
return users;
}
// 优化方案 - 单次查询
async function getUsersWithPostsOptimized() {
const result = await db.query(`
SELECT
u.*,
p.id as post_id,
p.title,
p.content
FROM users u
LEFT JOIN posts p ON u.id = p.user_id
ORDER BY u.id, p.id
`);
// 转换为嵌套结构
const usersMap = new Map();
for (const row of result) {
if (!usersMap.has(row.id)) {
usersMap.set(row.id, {
id: row.id,
name: row.name,
email: row.email,
posts: []
});
}
if (row.post_id) {
usersMap.get(row.id).posts.push({
id: row.post_id,
title: row.title,
content: row.content
});
}
}
return Array.from(usersMap.values());
}
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
// 添加测试用例
suite
.add('Original', function() {
findDuplicates(largeArray);
})
.add('Optimized', function() {
findDuplicatesOptimized(largeArray);
})
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run({ 'async': true });
// 使用Artillery进行负载测试
// artillery.yml
config:
target: 'http://localhost:3000'
phases:
- duration: 60
arrivalRate: 10
- duration: 120
arrivalRate: 50
- duration: 60
arrivalRate: 100
scenarios:
- name: "Load test API"
requests:
- get:
url: "/api/users"
- post:
url: "/api/users"
json:
name: "Test User"
email: "test@example.com"
// 性能监控中间件
const performanceMonitor = (req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
// 记录性能指标
console.log(`${req.method} ${req.path} - ${duration}ms`);
// 发送到监控系统
sendMetrics({
endpoint: req.path,
method: req.method,
duration: duration,
statusCode: res.statusCode,
timestamp: new Date().toISOString()
});
});
next();
};
// 内存使用监控
const memoryMonitor = () => {
const used = process.memoryUsage();
console.log('Memory Usage:');
for (let key in used) {
console.log(`${key}: ${Math.round(used[key] / 1024 / 1024)} MB`);
}
};
// 定期检查
setInterval(memoryMonitor, 30000);
# 性能分析报告
## 基本信息
- **分析范围**: 用户管理模块
- **技术栈**: Node.js, Express, MongoDB
- **数据规模**: 10万用户,100万帖子
- **测试环境**: AWS EC2 t3.large
- **分析时间**: 2024-01-15 14:00:00
## 性能概览
- **平均响应时间**: 245ms (目标: < 200ms)
- **95百分位响应时间**: 892ms (目标: < 500ms)
- **吞吐量**: 450 RPS (目标: > 1000 RPS)
- **CPU使用率**: 78% (目标: < 70%)
- **内存使用**: 1.8GB (目标: < 2GB)
- **性能评分**: 6.2/10
## 🔍 性能瓶颈分析
### 1. 数据库查询优化 (预计提升60%)
**问题**: N+1查询问题
**位置**: userService.js:45-62
**影响**: 用户列表加载缓慢
**当前实现**:
```javascript
// 执行101次数据库查询 (1次用户查询 + 100次帖子查询)
const users = await User.find();
for (const user of users) {
user.posts = await Post.find({ userId: user.id });
}
优化方案:
// 使用JOIN查询,只需1次数据库查询
const users = await User.aggregate([
{
$lookup: {
from: 'posts',
localField: '_id',
foreignField: 'userId',
as: 'posts'
}
}
]);
预期效果:
问题: 缺少有效的缓存机制 建议: 实施Redis缓存
缓存策略:
const cache = require('redis').createClient();
async function getCachedUser(userId) {
// 尝试从缓存获取
const cached = await cache.get(`user:${userId}`);
if (cached) {
return JSON.parse(cached);
}
// 从数据库获取
const user = await User.findById(userId);
// 存入缓存 (30分钟过期)
await cache.setex(`user:${userId}`, 1800, JSON.stringify(user));
return user;
}
问题: 用户搜索算法复杂度为O(n²) 优化: 使用倒排索引
优化前后对比:
| 操作 | 优化前 | 优化后 | 提升 |
|---|---|---|---|
| 用户列表 | 892ms | 245ms | 72% |
| 用户搜索 | 2300ms | 340ms | 85% |
| 用户创建 | 120ms | 85ms | 29% |
| 用户更新 | 95ms | 72ms | 24% |
并发用户: 1000 测试时长: 10分钟
| 指标 | 优化前 | 优化后 | 改善 |
|---|---|---|---|
| 平均响应时间 | 1.2s | 0.3s | 75% |
| 错误率 | 5.2% | 0.1% | 98% |
| 吞吐量 | 234 RPS | 892 RPS | 281% |
数据库查询优化 (2天)
基础缓存 (3天)
搜索引擎优化 (5天)
CDN集成 (2天)
alerts:
- name: "High Response Time"
condition: "avg_response_time > 500ms"
duration: "5m"
- name: "High CPU Usage"
condition: "cpu_usage > 80%"
duration: "10m"
- name: "Low Cache Hit Rate"
condition: "cache_hit_rate < 60%"
duration: "15m"
通过系统的性能分析和优化,可以显著提升应用程序的响应速度和用户体验。