performance-engineer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Performance Engineer

性能工程师

Specialist in analyzing and optimizing application performance, identifying bottlenecks, and implementing efficiency improvements.
专注于分析和优化应用性能、识别瓶颈并实施效率提升方案的专家。

When This Skill Activates

技能触发场景

Activates when you:
  • Report performance issues
  • Need performance optimization
  • Mention "slow" or "latency"
  • Want to improve efficiency
在你执行以下操作时触发:
  • 反馈性能问题
  • 需要进行性能优化
  • 提到「慢」或「延迟」相关内容
  • 想要提升效率

Performance Analysis Process

性能分析流程

Phase 1: Identify the Problem

阶段1:定位问题

  1. Define metrics
    • What's the baseline?
    • What's the target?
    • What's acceptable?
  2. Measure current performance
    bash
    # Response time
    curl -w "@curl-format.txt" -o /dev/null -s https://example.com/users
    
    # Database query time
    # Add timing logs to queries
    
    # Memory usage
    # Use profiler
  3. Profile the application
    bash
    # Node.js
    node --prof app.js
    
    # Python
    python -m cProfile app.py
    
    # Go
    go test -cpuprofile=cpu.prof
  1. 定义指标
    • 基准值是多少?
    • 优化目标是多少?
    • 可接受的阈值是多少?
  2. 测量当前性能
    bash
    # 响应时间
    curl -w "@curl-format.txt" -o /dev/null -s https://example.com/users
    
    # 数据库查询耗时
    # 给查询添加计时日志
    
    # 内存使用情况
    # 使用性能剖析工具
  3. 对应用做性能剖析
    bash
    # Node.js
    node --prof app.js
    
    # Python
    python -m cProfile app.py
    
    # Go
    go test -cpuprofile=cpu.prof

Phase 2: Find the Bottleneck

阶段2:查找瓶颈

Common bottleneck locations:
LayerCommon Issues
DatabaseN+1 queries, missing indexes, large result sets
APIOver-fetching, no caching, serial requests
ApplicationInefficient algorithms, excessive logging
FrontendLarge bundles, re-renders, no lazy loading
NetworkToo many requests, large payloads, no compression
常见瓶颈位置:
层级常见问题
数据库N+1 查询、索引缺失、结果集过大
API过度拉取、无缓存、串行请求
应用层算法效率低、日志输出过多
前端包体积过大、不必要重渲染、未使用懒加载
网络请求次数过多、 payload 过大、未开启压缩

Phase 3: Optimize

阶段3:优化

Database Optimization

数据库优化

N+1 Queries:
typescript
// Bad: N+1 queries
const users = await User.findAll();
for (const user of users) {
  user.posts = await Post.findAll({ where: { userId: user.id } });
}

// Good: Eager loading
const users = await User.findAll({
  include: [{ model: Post, as: 'posts' }]
});
Missing Indexes:
sql
-- Add index on frequently queried columns
CREATE INDEX idx_user_email ON users(email);
CREATE INDEX idx_post_user_id ON posts(user_id);
N+1 查询:
typescript
// Bad: N+1 queries
const users = await User.findAll();
for (const user of users) {
  user.posts = await Post.findAll({ where: { userId: user.id } });
}

// Good: Eager loading
const users = await User.findAll({
  include: [{ model: Post, as: 'posts' }]
});
索引缺失:
sql
-- 给高频查询的字段添加索引
CREATE INDEX idx_user_email ON users(email);
CREATE INDEX idx_post_user_id ON posts(user_id);

API Optimization

API 优化

Pagination:
typescript
// Always paginate large result sets
const users = await User.findAll({
  limit: 100,
  offset: page * 100
});
Field Selection:
typescript
// Select only needed fields
const users = await User.findAll({
  attributes: ['id', 'name', 'email']
});
Compression:
typescript
// Enable gzip compression
app.use(compression());
分页:
typescript
// 大结果集必须做分页
const users = await User.findAll({
  limit: 100,
  offset: page * 100
});
字段裁剪:
typescript
// 仅选择需要的字段
const users = await User.findAll({
  attributes: ['id', 'name', 'email']
});
压缩:
typescript
// 开启gzip压缩
app.use(compression());

Frontend Optimization

前端优化

Code Splitting:
typescript
// Lazy load routes
const Dashboard = lazy(() => import('./Dashboard'));
Memoization:
typescript
// Use useMemo for expensive calculations
const filtered = useMemo(() =>
  items.filter(item => item.active),
  [items]
);
Image Optimization:
  • Use WebP format
  • Lazy load images
  • Use responsive images
  • Compress images
代码分割:
typescript
// 路由懒加载
const Dashboard = lazy(() => import('./Dashboard'));
记忆化缓存:
typescript
// 高开销计算使用useMemo缓存
const filtered = useMemo(() =>
  items.filter(item => item.active),
  [items]
);
图片优化:
  • 使用WebP格式
  • 图片懒加载
  • 使用响应式图片
  • 压缩图片体积

Phase 4: Verify

阶段4:验证

  1. Measure again
  2. Compare to baseline
  3. Ensure no regressions
  4. Document the improvement
  1. 再次测量性能
  2. 和基准值做对比
  3. 确保没有引入功能回归
  4. 记录优化效果

Performance Targets

性能指标目标

MetricTargetCritical Threshold
API Response (p50)< 100ms< 500ms
API Response (p95)< 500ms< 1s
API Response (p99)< 1s< 2s
Database Query< 50ms< 200ms
Page Load (FMP)< 2s< 3s
Time to Interactive< 3s< 5s
Memory Usage< 512MB< 1GB
指标目标值临界阈值
API响应 (p50)< 100ms< 500ms
API响应 (p95)< 500ms< 1s
API响应 (p99)< 1s< 2s
数据库查询< 50ms< 200ms
页面加载 (FMP)< 2s< 3s
可交互时间< 3s< 5s
内存使用< 512MB< 1GB

Common Optimizations

常见优化手段

Caching Strategy

缓存策略

typescript
// Cache expensive computations
const cache = new Map();

async function getUserStats(userId: string) {
  if (cache.has(userId)) {
    return cache.get(userId);
  }

  const stats = await calculateUserStats(userId);
  cache.set(userId, stats);

  // Invalidate after 5 minutes
  setTimeout(() => cache.delete(userId), 5 * 60 * 1000);

  return stats;
}
typescript
// 缓存高开销计算结果
const cache = new Map();

async function getUserStats(userId: string) {
  if (cache.has(userId)) {
    return cache.get(userId);
  }

  const stats = await calculateUserStats(userId);
  cache.set(userId, stats);

  // 5分钟后失效
  setTimeout(() => cache.delete(userId), 5 * 60 * 1000);

  return stats;
}

Batch Processing

批量处理

typescript
// Bad: Individual requests
for (const id of userIds) {
  await fetchUser(id);
}

// Good: Batch request
await fetchUsers(userIds);
typescript
// Bad: 单次请求逐个查询
for (const id of userIds) {
  await fetchUser(id);
}

// Good: 批量请求
await fetchUsers(userIds);

Debouncing/Throttling

防抖/节流

typescript
// Debounce search input
const debouncedSearch = debounce(search, 300);

// Throttle scroll events
const throttledScroll = throttle(handleScroll, 100);
typescript
// 搜索输入防抖
const debouncedSearch = debounce(search, 300);

// 滚动事件节流
const throttledScroll = throttle(handleScroll, 100);

Performance Monitoring

性能监控

Key Metrics

核心指标

  • Response Time: Time to process request
  • Throughput: Requests per second
  • Error Rate: Failed requests percentage
  • Memory Usage: Heap/RAM used
  • CPU Usage: Processor utilization
  • 响应时间:处理请求的耗时
  • 吞吐量:每秒处理的请求数
  • 错误率:请求失败的占比
  • 内存使用:堆/内存占用量
  • CPU使用率:处理器利用率

Monitoring Tools

监控工具

ToolPurpose
LighthouseFrontend performance
New RelicAPM monitoring
DatadogInfrastructure monitoring
PrometheusMetrics collection
工具用途
Lighthouse前端性能检测
New RelicAPM性能监控
Datadog基础设施监控
Prometheus指标采集

Scripts

脚本

Profile application:
bash
python scripts/profile.py
Generate performance report:
bash
python scripts/perf_report.py
应用性能剖析:
bash
python scripts/profile.py
生成性能报告:
bash
python scripts/perf_report.py

References

参考资料

  • references/optimization.md
    - Optimization techniques
  • references/monitoring.md
    - Monitoring setup
  • references/checklist.md
    - Performance checklist
  • references/optimization.md
    - 优化技巧
  • references/monitoring.md
    - 监控配置
  • references/checklist.md
    - 性能检查清单