引言
性能优化最常见的错误是先改代码再测量。没有基线和剖析,优化可能只是把瓶颈从一处移到另一处,甚至引入正确性问题。
先测量
定义用户可感知的指标:首屏、交互延迟、请求 p95。用真实流量或接近真实的负载建立基线,再用 profiler、trace 和慢查询日志定位热点。区分 CPU、I/O、锁等待和网络延迟。
后端瓶颈
常见问题包括 N+1 查询、缺失索引、过大响应、串行远程调用和无界并发。用 EXPLAIN ANALYZE 验证查询,用连接池和批量接口减少往返,用缓存和预计算消除重复工作。优化后重新测量,确认瓶颈确实移动。
前端瓶颈
减少关键路径 JavaScript、拆分代码、优化图片和字体、避免布局抖动。用 Lighthouse 和真实用户指标验证,而不只是本地实验室数据。首屏优先,延迟加载非关键资源。
缓存与预算
缓存是收益乘数,但必须定义失效策略和可接受陈旧度。把 bundle 大小、LCP、p95 设为 CI 预算,超过即失败。生产持续监控并设置告警,防止性能悄悄回退。
结论
性能是持续工程,不是一次性任务。测量、修复、预算和监控形成闭环,才能让优化成果在后续发布中保持。
代码示例
// Node.js: profile a request with the built-in inspector.
// Run: node --inspect, open chrome://inspect, start a CPU profile, hit the endpoint, stop.
// Or use clinic.js for a flame graph:
// clinic flame -- node server.js -> clinic flame --visualize
// N+1: one query for posts, then one per post for the author.
const posts = await db.posts.findMany(); // 1 query
for (const p of posts) p.author = await db.users.findUnique({ where: { id: p.authorId } }); // N queries
// Fixed: one query with a join (Prisma relation load).
const posts = await db.posts.findMany({ include: { author: true } }); // 1 query
// Break a long task so the main thread can paint and respond.
async function processLargeList(items: Item[]) {
const CHUNK = 50;
for (let i = 0; i < items.length; i += CHUNK) {
processChunk(items.slice(i, i + CHUNK));
if (i % 500 === 0) await scheduler.yield(); // yield to let the browser respond to input
}
}
// HTTP caching for a hashed asset: immutable, cache forever.
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
// In-memory cache for an expensive computation with TTL.
const cache = new Map<string, { value: Result; expires: number }>();
async function getCached(key: string, ttlMs: number, compute: () => Promise<Result>) {
const hit = cache.get(key);
if (hit && hit.expires > Date.now()) return hit.value;
const value = await compute();
cache.set(key, { value, expires: Date.now() + ttlMs });
return value;
}
// A budget check in CI (conceptual).
const budget = { bundleGzipKb: 150, lcpMs: 2000, cls: 0.05 };
const actual = await measureBuild();
if (actual.bundleGzipKb > budget.bundleGzipKb) {
console.error(`Bundle ${actual.bundleGzipKb}KB exceeds budget ${budget.bundleGzipKb}KB`);
process.exit(1);
}
EXPLAIN ANALYZE
SELECT orders.*, customers.name FROM orders
JOIN customers ON orders.customer_id = customers.id
WHERE orders.status = 'pending' AND orders.created_at > NOW() - INTERVAL '7 days'
ORDER BY orders.created_at DESC LIMIT 50;
<img
src="/photo-800.webp"
srcset="/photo-400.webp 400w, /photo-800.webp 800w, /photo-1200.webp 1200w"
sizes="(max-width: 600px) 400px, 800px"
width="800" height="600"
loading="lazy" decoding="async"
alt="...">