-
-
Notifications
You must be signed in to change notification settings - Fork 369
perf: Benchmarks and optimizations #1527
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kibertoad
wants to merge
5
commits into
open-circle:main
Choose a base branch
from
kibertoad:perf/variant-enum-object-fastpaths
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c135c88
Benchmarks and optimizations
kibertoad 05f65a0
Adjust comments
kibertoad d03cc7d
Address review comments
kibertoad c8755bf
Address review comments II
kibertoad 568c6b2
Merge branch 'main' into perf/variant-enum-object-fastpaths
yslpn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| # Benchmarking | ||
|
|
||
| Valibot has a runtime benchmark suite for catching performance regressions and proving | ||
| optimizations. It runs on [Vitest's built-in `bench`](https://vitest.dev/api/#bench), so there is | ||
| no extra dependency. | ||
|
|
||
| ## Running | ||
|
|
||
| ```sh | ||
| cd library | ||
| pnpm bench | ||
| ``` | ||
|
|
||
| This runs every `library/bench/*.bench.ts` file and prints throughput per case (`hz`, | ||
| operations per second, higher is better) along with latency percentiles. To run a single file, | ||
| pass a filter: | ||
|
|
||
| ```sh | ||
| pnpm bench variant | ||
| ``` | ||
|
|
||
| ## What is covered | ||
|
|
||
| The suite lives in `library/bench/` and targets the runtime hot paths: | ||
|
|
||
| - `variant.bench.ts` / `variant-async.bench.ts` — discriminated-union dispatch (hit first, middle, | ||
| last option, and miss). | ||
| - `enum.bench.ts` / `picklist.bench.ts` — membership against a large option list (hit and miss). | ||
| - `object.bench.ts` — object validation (all keys present, and a missing required key). | ||
| - `array.bench.ts`, `string-pipe.bench.ts` — regression guards for the array and pipe paths; they | ||
| should stay flat and signal a regression if they don't. | ||
|
|
||
| ## Results | ||
|
|
||
| Record before/after numbers and the speedups they prove when an optimization changes the numbers, | ||
| capturing both the baseline and the optimized run on the same machine. | ||
|
|
||
| ## Adding a benchmark | ||
|
|
||
| Create `library/bench/<name>.bench.ts`: | ||
|
|
||
| ```ts | ||
| import { bench, describe } from 'vitest'; | ||
| import * as v from '../src/index.ts'; | ||
|
|
||
| // Build the schema and inputs once, outside bench(). | ||
| const schema = v.object({ id: v.number(), name: v.string() }); | ||
| const input = { id: 1, name: 'test' }; | ||
|
|
||
| describe('object', () => { | ||
| bench('valid', () => { | ||
| return v.safeParse(schema, input); | ||
| }); | ||
| }); | ||
| ``` | ||
|
|
||
| Guidelines: | ||
|
|
||
| - Build schemas and inputs once outside `bench()` so you measure validation, not setup. | ||
| - Use `safeParse` / `safeParseAsync` rather than `parse` to avoid throw overhead skewing results. | ||
| - Return the parse result from `bench()` so the engine cannot drop the call as dead code. | ||
| - Absolute `hz` values depend on hardware, so compare the baseline and optimized numbers on the same | ||
| machine, not across machines. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import { bench, describe } from 'vitest'; | ||
| import * as v from '../src/index.ts'; | ||
|
|
||
| // Regression guard for array validation throughput. | ||
| const schema = v.array(v.object({ id: v.number(), name: v.string() })); | ||
|
|
||
| const input = Array.from({ length: 100 }, (_, i) => ({ | ||
| id: i, | ||
| name: `item_${i}`, | ||
| })); | ||
|
|
||
| describe('array (100 objects)', () => { | ||
| bench('valid', () => { | ||
| return v.safeParse(schema, input); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import { bench, describe } from 'vitest'; | ||
| import * as v from '../src/index.ts'; | ||
|
|
||
| // Large string enum (~200 members). | ||
| const enumObject: Record<string, string> = {}; | ||
| for (let i = 0; i < 200; i++) { | ||
| enumObject[`KEY_${i}`] = `value_${i}`; | ||
| } | ||
| const schema = v.enum(enumObject); | ||
|
|
||
| const hitFirst = 'value_0'; | ||
| const hitLast = 'value_199'; | ||
| const miss = 'value_missing'; | ||
|
|
||
| describe('enum (200 members)', () => { | ||
| bench('hit first', () => { | ||
| return v.safeParse(schema, hitFirst); | ||
| }); | ||
|
|
||
| bench('hit last', () => { | ||
| return v.safeParse(schema, hitLast); | ||
| }); | ||
|
|
||
| bench('miss', () => { | ||
| return v.safeParse(schema, miss); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { bench, describe } from 'vitest'; | ||
| import * as v from '../src/index.ts'; | ||
|
|
||
| // Flat schema of primitive entries so the measurement isolates the top-level | ||
| // object entry loop, not array or nested-object validation. | ||
| const schema = v.object({ | ||
| id: v.number(), | ||
| name: v.string(), | ||
| active: v.boolean(), | ||
| count: v.number(), | ||
| label: v.string(), | ||
| enabled: v.boolean(), | ||
| }); | ||
|
|
||
| const fullInput = { | ||
| id: 1, | ||
| name: 'test', | ||
| active: true, | ||
| count: 2, | ||
| label: 'x', | ||
| enabled: false, | ||
| }; | ||
|
|
||
| const missingKeyInput = { | ||
| id: 1, | ||
| name: 'test', | ||
| active: true, | ||
| count: 2, | ||
| label: 'x', | ||
| // `enabled` missing -> required-key path | ||
| }; | ||
|
|
||
| describe('object', () => { | ||
| bench('all keys present (happy path)', () => { | ||
| return v.safeParse(schema, fullInput); | ||
| }); | ||
|
|
||
| bench('missing required key', () => { | ||
| return v.safeParse(schema, missingKeyInput); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import { bench, describe } from 'vitest'; | ||
| import * as v from '../src/index.ts'; | ||
|
|
||
| // Large allow-list, e.g. an ISO-style country/option code set. | ||
| const values = Array.from({ length: 200 }, (_, i) => `code_${i}`); | ||
| const schema = v.picklist(values); | ||
|
|
||
| const hitFirst = 'code_0'; | ||
| const hitLast = 'code_199'; | ||
| const miss = 'code_missing'; | ||
|
|
||
| describe('picklist (200 options)', () => { | ||
| bench('hit first', () => { | ||
| return v.safeParse(schema, hitFirst); | ||
| }); | ||
|
|
||
| bench('hit last', () => { | ||
| return v.safeParse(schema, hitLast); | ||
| }); | ||
|
|
||
| bench('miss', () => { | ||
| return v.safeParse(schema, miss); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import { bench, describe } from 'vitest'; | ||
| import * as v from '../src/index.ts'; | ||
|
|
||
| // Regression guard for pipe execution throughput. | ||
| const schema = v.pipe( | ||
| v.string(), | ||
| v.minLength(3), | ||
| v.maxLength(32), | ||
| v.trim() | ||
| ); | ||
|
|
||
| const input = 'hello world'; | ||
|
|
||
| describe('string pipe', () => { | ||
| bench('valid', () => { | ||
| return v.safeParse(schema, input); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import { bench, describe } from 'vitest'; | ||
| import * as v from '../src/index.ts'; | ||
|
|
||
| // Flat async discriminated union with 10 options, each keyed by a literal | ||
| // `type`. Discriminator entries are sync (literal); the variant run is async. | ||
| const options = Array.from({ length: 10 }, (_, i) => | ||
| v.object({ | ||
| type: v.literal(`option_${i}`), | ||
| value: v.number(), | ||
| label: v.string(), | ||
| }) | ||
| ); | ||
| // @ts-expect-error - runtime array is fine for the benchmark | ||
| const schema = v.variantAsync('type', options); | ||
|
|
||
| const firstInput = { type: 'option_0', value: 1, label: 'a' }; | ||
| const middleInput = { type: 'option_5', value: 1, label: 'a' }; | ||
| const lastInput = { type: 'option_9', value: 1, label: 'a' }; | ||
| const missInput = { type: 'option_x', value: 1, label: 'a' }; | ||
|
|
||
| describe('variantAsync (10 options)', () => { | ||
| bench('hit first option', async () => { | ||
| return await v.safeParseAsync(schema, firstInput); | ||
| }); | ||
|
|
||
| bench('hit middle option', async () => { | ||
| return await v.safeParseAsync(schema, middleInput); | ||
| }); | ||
|
|
||
| bench('hit last option', async () => { | ||
| return await v.safeParseAsync(schema, lastInput); | ||
| }); | ||
|
|
||
| bench('miss (invalid discriminator)', async () => { | ||
| return await v.safeParseAsync(schema, missInput); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import { bench, describe } from 'vitest'; | ||
| import * as v from '../src/index.ts'; | ||
|
|
||
| // Flat discriminated union with 10 options, each keyed by a literal `type`. | ||
| const options = Array.from({ length: 10 }, (_, i) => | ||
| v.object({ | ||
| type: v.literal(`option_${i}`), | ||
| value: v.number(), | ||
| label: v.string(), | ||
| }) | ||
| ); | ||
| // @ts-expect-error - runtime array is fine for the benchmark | ||
| const schema = v.variant('type', options); | ||
|
|
||
| const firstInput = { type: 'option_0', value: 1, label: 'a' }; | ||
| const middleInput = { type: 'option_5', value: 1, label: 'a' }; | ||
| const lastInput = { type: 'option_9', value: 1, label: 'a' }; | ||
| const missInput = { type: 'option_x', value: 1, label: 'a' }; | ||
|
|
||
| describe('variant (10 options)', () => { | ||
| bench('hit first option', () => { | ||
| return v.safeParse(schema, firstInput); | ||
| }); | ||
|
|
||
| bench('hit middle option', () => { | ||
| return v.safeParse(schema, middleInput); | ||
| }); | ||
|
|
||
| bench('hit last option', () => { | ||
| return v.safeParse(schema, lastInput); | ||
| }); | ||
|
|
||
| bench('miss (invalid discriminator)', () => { | ||
| return v.safeParse(schema, missInput); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -144,8 +144,18 @@ export function enum_( | |
| return _getStandardProps(this); | ||
| }, | ||
| '~run'(dataset, config) { | ||
| // Lazily cache the options as a set for O(1) membership checks. This is | ||
| // faster than `Array.includes` for large enums and uses SameValueZero | ||
| // comparison, so behavior is identical. The set is built once and assumes | ||
| // `options` is not mutated after schema creation, which matches the | ||
| // existing contract: `expects` is already precomputed from `options` | ||
| // above, so a post-creation mutation would desync the error message | ||
| // regardless. | ||
| // @ts-expect-error | ||
| if (this.options.includes(dataset.value)) { | ||
| const optionsSet: Set<unknown> = (this._optionsSet ??= new Set( | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What do you think about not writing the cache to the object's observable properties?
The cache can be stored at the module level. |
||
| this.options | ||
| )); | ||
| if (optionsSet.has(dataset.value)) { | ||
| // @ts-expect-error | ||
| dataset.typed = true; | ||
| } else { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Benchmarks currently measure performance, but they don't automatically catch regressions: the vitest bench simply prints numbers. A true regression guard requires a CI baseline/comparison service.
Any ideas on how to add this?