Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Vitest 3.x reference skill covering configuration, test/describe APIs, mocking, coverage, snapshots, and concurrency.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/features-benchmarking.md
1---2name: benchmarking3description: Write benchmarks with the v5 bench test-context fixture (Tinybench)4---56# Benchmarking (v5)78In v5 the benchmark API was rewritten: `bench` is **no longer a top-level import**. It is a [test-context fixture](features-context.md) used inside a regular `test()`, available only in files matched by `benchmark.include` (default `**/*.{bench,benchmark}.?(c|m)[jt]s?(x)`). Benchmarks are powered by [Tinybench](https://github.com/tinylibs/tinybench).910## Defining & Running1112```ts13import { expect, test } from 'vitest'1415test('parse performance', async ({ bench }) => {16// bench() registers; .run() executes and returns the result17const result = await bench('parse', () => {18const data = JSON.parse('{"key":"value"}')19use(data) // consume the result — engines may eliminate dead code20}).run()2122expect(result.throughput.mean).toBeGreaterThan(10_000)23})24```2526Run benchmarks:2728```bash29vitest bench # only benchmarks (implicitly enables them)30vitest bench parser # filter by filename31vitest bench -t JSON # filter by test name32```3334Set `benchmark: { enabled: true }` to run them alongside regular tests in a separate isolated group.3536## Comparing Implementations3738```ts39test('compare parsers', async ({ bench }) => {40const result = await bench.compare(41bench('JSON.parse', () => { JSON.parse(input) }),42bench('custom', { beforeEach: () => reset() }, () => { customParse(input) }),43{ iterations: 100, time: 1000 }, // shared Tinybench options (last arg)44)4546// Assertion matchers (delta avoids flaky failures)47expect(result.get('JSON.parse')).toBeFasterThan(result.get('custom'), { delta: 0.1 })48expect(result.get('custom')).toBeSlowerThan(result.get('JSON.parse'))49})50```5152`bench.compare` interleaves iterations to reduce environmental bias and prints a comparison table after the test.5354## Storing & Replaying Baselines5556```ts57test('compare against baseline', async ({ bench }) => {58await bench.compare(59bench('current', { writeResult: './benchmarks/parse.json' }, () => parse(input)),60bench.from('previous', './benchmarks/parse.json'), // reads a stored result, no run61bench.from('remote', () => fetch(url).then(r => r.json())),62)63})64```6566- `writeResult` overwrites the JSON file on every successful run (no skip-when-cached).67- `bench.from(name, source)` reads a stored result without invoking any function.68- For multi-project workspaces, pass `{ perProject: true }` and use `${projectName}` in `writeResult` paths to collect a cross-project comparison table.6970## Stability Notes7172- Benchmark files run sequentially and never in parallel; `retry` and the `delta` option reduce flakiness.73- Consume the result inside the bench fn — JS engines eliminate side-effect-free code.74- In Node mode every imported binding goes through Vite's module-runner getter; store hot references locally (`const _parse = parse`), benchmark the built package, or disable `experimental.viteModuleRunner` for the bench project.7576## v5 Migration7778- `bench` top-level import → `({ bench })` from the test context79- `bench.skip/only/todo` removed → use `test.skip/only/todo` on the surrounding test80- `benchmark.reporters`/`outputFile`/`compare`/`outputJson` and `--compare`/`--outputJson` removed → use `--reporter=json --outputFile` (JSON now has a `benchmarks` field)8182## Key Points8384- Benchmarks live in `*.bench.ts` files and run inside `test()` via `{ bench }`85- Use `bench.compare` + `toBeFasterThan`/`toBeSlowerThan` (with `delta`) for relative perf86- Persist baselines with `writeResult` and replay with `bench.from`8788<!--89Source references:90- https://vitest.dev/guide/benchmarking91- https://vitest.dev/guide/test-context#bench92-->93