Setting the file. One moment.
Subchapter 13.11
references/features-benchmarking.mdMarkdown4 KBView on GitHub
In v5 the benchmark API was rewritten: bench is no longer a top-level import. It is a test-context fixture used inside a regular test(), available only in files matched by benchmark.include (default ). Benchmarks are powered by .
**/*.{bench,benchmark}.?(c|m)[jt]s?(x)import { expect, test } from 'vitest'
test('parse performance', async ({ bench }) => {
// bench() registers; .run() executes and returns the result
const result = await bench('parse', () => {
const data = JSON.parse('{"key":"value"}')
use(data) // consume the result — engines may eliminate dead code
}).run()
expect(result.throughput.mean).toBeGreaterThan(10_000)
})Run benchmarks:
vitest bench # only benchmarks (implicitly enables them)
vitest bench parser # filter by filename
vitest bench -t JSON # filter by test nameSet benchmark: { enabled: true } to run them alongside regular tests in a separate isolated group.
test('compare parsers', async ({ bench }) => {
const result = await bench.compare(
bench('JSON.parse', () => { JSON.parse(input) }),
bench('custom', { beforeEach: () => reset() }, () => { customParse(input) }),
{ iterations: 100, time: 1000 }, // shared Tinybench options (last arg)
)
// Assertion matchers (delta avoids flaky failures)
expect(result.get('JSON.parse')).toBeFasterThan(result.get('custom'), { delta: 0.1 })
expect(result.get('custom')).toBeSlowerThan(result.get('JSON.parse'))
})bench.compare interleaves iterations to reduce environmental bias and prints a comparison table after the test.
test('compare against baseline', async ({ bench }) => {
await bench.compare(
bench('current', { writeResult: './benchmarks/parse.json' }, () => parse(input)),
bench.from('previous', './benchmarks/parse.json'), // reads a stored result, no run
bench.from('remote', () => fetch(url).then(r => r.json())),
)
})writeResult overwrites the JSON file on every successful run (no skip-when-cached).bench.from(name, source) reads a stored result without invoking any function.{ perProject: true } and use ${projectName} in writeResult paths to collect a cross-project comparison table.retry and the delta option reduce flakiness.const _parse = parse), benchmark the built package, or disable experimental.viteModuleRunner for the bench project.bench top-level import → ({ bench }) from the test contextbench.skip/only/todo removed → use test.skip/only/todo on the surrounding testbenchmark.reporters/outputFile/compare/outputJson and --compare/--outputJson removed → use --reporter=json --outputFile (JSON now has a benchmarks field)*.bench.ts files and run inside test() via { bench }bench.compare + toBeFasterThan/toBeSlowerThan (with delta) for relative perfwriteResult and replay with bench.from