数据与分析
performance-optimization
优化应用的前端、后端、查询和数据库性能。当存在性能要求、怀疑出现性能回归、Core Web Vitals 或加载时间需要改进、需要修复 N+1 查询模式,或 profiling 暴露出瓶颈时使用。
vinvcn · 已有静态检查记录
安装与使用
运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。
npx skills add vinvcn/addyosmani-agent-skills-zh --skill performance-optimization技能说明
name: performance-optimization description: 优化应用的前端、后端、查询和数据库性能。当存在性能要求、怀疑出现性能回归、Core Web Vitals 或加载时间需要改进、需要修复 N+1 查询模式,或 profiling 暴露出瓶颈时使用。
性能优化
概览
先测量,再优化。没有测量的性能工作就是猜测 —— 而猜测会导致过早优化,增加复杂度却没改善真正要紧的东西。先 profile,找到真正的瓶颈,修复它,再测一遍。只优化被测量证明要紧的部分。
何时使用
- spec 中有性能要求(加载时间预算、响应时间 SLA)
- 用户或监控报告了卡顿
- Core Web Vitals 分数低于阈值
- 你怀疑某次变更引入了回归
- 构建处理大数据集或高流量的功能
何时不用: 在没有问题证据之前不要优化。过早优化带来的复杂度,比它换来的性能更贵。
Core Web Vitals 目标
| 指标 | Good | Needs Improvement | Poor |
|---|---|---|---|
| LCP(Largest Contentful Paint) | ≤ 2.5s | ≤ 4.0s | > 4.0s |
| INP(Interaction to Next Paint) | ≤ 200ms | ≤ 500ms | > 500ms |
| CLS(Cumulative Layout Shift) | ≤ 0.1 | ≤ 0.25 | > 0.25 |
优化工作流
1. MEASURE → Establish baseline with real data
2. IDENTIFY → Find the actual bottleneck (not assumed)
3. FIX → Address the specific bottleneck
4. VERIFY → Measure again; keep or revert
5. GUARD → Add monitoring or tests to prevent regression
步骤 1: 测量
两种互补的方法 —— 都要用:
- Synthetic(Lighthouse、DevTools Performance 标签页): 条件受控、可复现。最适合 CI 回归检测和隔离具体问题。
- RUM(web-vitals library、CrUX): 真实条件下的真实用户数据。要验证一次修复确实改善了用户体验,这是必需的。
前端:
# Synthetic: Lighthouse in Chrome DevTools (or CI)
# Chrome DevTools → Performance tab → Record
# Chrome DevTools MCP → Performance trace
# RUM: Web Vitals library in code
import { onLCP, onINP, onCLS } from 'web-vitals';
onLCP(console.log);
onINP(console.log);
onCLS(console.log);
后端:
# Response time logging
# Application Performance Monitoring (APM)
# Database query logging with timing
# Simple timing
console.time('db-query');
const result = await db.query(...);
console.timeEnd('db-query');
从哪里开始测量
用症状来决定先测什么:
What is slow?
├── First page load
│ ├── Large bundle? --> Measure bundle size, check code splitting
│ ├── Slow server response? --> Measure TTFB in DevTools Network waterfall
│ │ ├── DNS long? --> Add dns-prefetch / preconnect for known origins
│ │ ├── TCP/TLS long? --> Enable HTTP/2, check edge deployment, keep-alive
│ │ └── Waiting (server) long? --> Profile backend, check queries and caching
│ └── Render-blocking resources? --> Check network waterfall for CSS/JS blocking
├── Interaction feels sluggish
│ ├── UI freezes on click? --> Profile main thread, look for long tasks (>50ms)
│ ├── Form input lag? --> Check re-renders, controlled component overhead
│ └── Animation jank? --> Check layout thrashing, forced reflows
├── Page after navigation
│ ├── Data loading? --> Measure API response times, check for waterfalls
│ └── Client rendering? --> Profile component render time, check for N+1 fetches
└── Backend / API
├── Single endpoint slow? --> Profile database queries, check indexes
├── All endpoints slow? --> Check connection pool, memory, CPU
└── Intermittent slowness? --> Check for lock contention, GC pauses, external deps
步骤 2: 识别瓶颈
按类别划分的常见瓶颈:
前端:
| 症状 | 可能原因 | 排查方向 |
|---|---|---|
| LCP 慢 | 图片过大、render-blocking 资源、服务器慢 | 查看 network waterfall、图片尺寸 |
| CLS 高 | 图片没有尺寸、晚加载的内容、字体偏移 | 查看 layout shift 归因 |
| INP 差 | 主线程上过重的 JavaScript、大型 DOM 更新 | 在 Performance trace 中查看 long tasks |
| 首次加载慢 | bundle 过大、网络请求过多 | 检查 bundle size、code splitting |
后端:
| 症状 | 可能原因 | 排查方向 |
|---|---|---|
| API 响应慢 | N+1 查询、缺失索引、未优化的查询 | 查看数据库查询日志 |
| 内存增长 | 泄漏的引用、无界缓存、大 payload | Heap snapshot 分析 |
| CPU 尖峰 | 同步的重计算、正则回溯 | CPU profiling |
| 高延迟 | 缺少缓存、冗余计算、网络跳数 | 沿调用栈 trace 请求 |
步骤 3: 修复常见反模式
N+1 Queries(后端)
// BAD: N+1 — one query per task for the owner
const tasks = await db.tasks.findMany();
for (const task of tasks) {
task.owner = await db.users.findUnique({ where: { id: task.ownerId } });
}
// GOOD: Single query with join/include
const tasks = await db.tasks.findMany({
include: { owner: true },
});
Unbounded Data Fetching
// BAD: Fetching all records
const allTasks = await db.tasks.findMany();
// GOOD: Paginated with limits
const tasks = await db.tasks.findMany({
take: 20,
skip: (page - 1) * 20,
orderBy: { createdAt: 'desc' },
});
Queries That Ignore Their Index
"加个索引"是猜测。查询计划才是测量:
EXPLAIN ANALYZE
SELECT id, title FROM tasks
WHERE owner_id = 42 ORDER BY created_at DESC LIMIT 20;
输出里的三样东西决定怎么修:
| 你看到什么 | 它意味着什么 |
|---|---|
在你预期有索引的大表上出现 Seq Scan | 这个谓词没有可用的索引 |
估算的 rows= 与实际相差一个数量级 | 统计信息过期;planner 基于错误信息做选择 |
scan 之上有一个 Sort 节点 | 索引覆盖了过滤条件,但没覆盖 ORDER BY |
按查询的形状建索引,而不是孤立地看某一列。在复合索引里,等值列在前,范围或排序列在后:
CREATE INDEX idx_tasks_owner_created ON tasks (owner_id, created_at DESC);
索引帮不上忙的情况:
| 情形 | 原因 |
|---|---|
低选择性,查询占主导的值(一个 95% 都是 active 的 status 列,且过滤条件就是 active) | 顺序扫描确实更便宜,planner 会忽略索引。反过来,过滤罕见值时结论相反,此时 partial index 非常合适 |
前导通配符(LIKE '%term') | B-tree 没有前缀就无法 seek;需要 trigram 或 full-text |
列上有函数(WHERE lower(email) = ?) | 普通列索引不可用;改为对该表达式建索引 |
| 写多的表 | 每个索引都是对每次 INSERT/UPDATE 的抽税;要测写入成本,不能只看读取收益 |
之后重跑一次 EXPLAIN ANALYZE。一个没改变执行计划的索引应当 revert(Step 4),而且它并不免费:每次写入它都在付出成本。
Connection Pool Exhaustion
Signature 很有辨识度:所有 endpoints 同时变慢,慢的时间花在等连接而不是执行上,数据库则报告大量空闲 sessions。
// BAD: a pool per request or per module — under serverless this multiplies
// by instance count and exhausts the database's connection limit
// GOOD: one pool per process, sized against the database's ceiling
const pool = new Pool({
max: 10, // instances × max must stay under max_connections
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 5_000, // fail fast instead of queueing forever
});
更大不等于更快。 比数据库实际能并发执行的数量还大的 pool,只是把队列从你的应用挪到数据库里 —— 那里更难看见。当实例数量无上限(serverless、autoscaling)时,解法是一个做连接复用的代理(pgbouncer、RDS Proxy),而不是调高 max。
Missing Image Optimization(前端)
<!-- BAD: No dimensions, no format optimization -->
<img src="/hero.jpg" />
<!-- GOOD: Hero / LCP image — art direction + re
阅读完整来源 ↗