性能测试
Benchmark hot paths, detect regressions, and measure 加载使用 Vitest bench and k6.
你将学到
- difference 之间 micro-benchmarks and 加载测试
- 编写 benchmarks 使用 Vitest bench and Benchmark.js
- Detecting 性能 regressions in CI
- 加载测试 APIs 使用 k6 and measuring throughput
概念讲解
Two Kinds of Performance Tests
Micro-benchmarks measure the speed of a small piece of code — a sort function, a parser, a reducer — so you can compare implementations and catch regressions. Load tests drive a running system with realistic or extreme traffic to find its limits: requests per second, latency percentiles, and the breaking point. Both matter; they answer different questions.
Vitest bench
Vitest ships a bench API for micro-benchmarks. bench("排序 1000 项", () => { 排序(数据) }) runs the function many times, warms up the JIT, and reports operations per second and average time. Run with vitest bench and compare results across runs. Keep benchmarks isolated (no I/O, no randomness) and vary the input size so you see the scaling curve, not just one point.
Regression Detection
A benchmark is only useful if you track its results. Store baseline numbers and fail CI when a benchmark regresses beyond a threshold (say, 10% slower). Beware of noise: CI machines are virtualized and variable, so use a tolerance band and prefer relative comparisons (before vs after a change) over absolute targets. Run benchmarks on a dedicated, quiet machine for the most stable numbers.
Load Testing with k6
k6 (and Artillery, wrk) drives a deployed API with scripted traffic and reports latency percentiles (p50, p95, p99) and throughput. Write a k6 script that ramps virtual users from 10 to 1000 over a minute, hits your endpoints, and asserts that p95 latency stays under 200ms. Run load tests against a staging environment, never production, and use them to find the bottleneck (database, connection pool, garbage collection) before users do.
In Practice
For micro-benchmarks, always compare two implementations side by side rather than measuring one in isolation — relative comparison cancels out machine noise. Vary the input size (10, 100, 1000, 10000) to see the scaling curve and catch accidental quadratic behavior. For load tests, start with a small ramp to find the shape of the performance curve, then design a sustained test that holds the system at its expected peak. Watch the p99 latency, not just the average — a low average with a high p99 means some users are waiting seconds. After a load test, correlate the bottlenecks with profiling data (CPU flames, database slow queries) so you fix the cause rather than throwing more hardware at the symptom. Check performance regressions in CI with a tolerance band, since virtualized CI machines are noisy.
示例代码
// sort.bench.ts — micro-benchmark with Vitest
import { bench, describe } from "vitest";
import { fastSort } from "./fastSort";
import { builtinSort } from "./builtinSort";
const data = Array.from({ length: 1000 }, (_, i) => Math.random() * i);
describe("sorting 1000 numbers", () => {
bench("fastSort", () => {
fastSort([...data]);
});
bench("builtinSort", () => {
builtinSort([...data]);
});
});
// Run: npx vitest bench
// Reports ops/sec and average time for each implementation.
bench 运行每个函数许多次数 and reports 操作每 其次. Comparing two implementations 边通过边 shows 哪个是 faster and 通过如何 much.
动手试一试
- HTTP 请求 Tester
Measure latency 的端点之前加载测试它们.
- Crontab Generator
Schedule recurring 性能运行针对 staging.
常见错误
错误写法
Benchmarking 使用 cold 数据 JIT 有从不 seen
正确做法
Let benchmark warm 上 (Vitest 做这个 automatically) and 运行 enough iterations 那个 JIT optimizes. One-shot timing 是 meaningless.
错误写法
加载测试 production
正确做法
总是加载测试 staging or isolated 环境. 加载测试针对 production 能 overload 真实用户 and 触发 outages.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。