Skip to content

Improve discriminated union implementation #4556

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

Merged
merged 6 commits into from
May 28, 2025
Merged

Conversation

colinhacks
Copy link
Owner

@colinhacks colinhacks commented May 28, 2025

Remove the disc field from internals and replace with a simple propValues map. This makes introspection into discriminator values far easier, simplifies the parsing logic, and results in a 2x performance improvement:

$ cd packages/bench
$ pnpm bench discriminated-union
cpu: Apple M1 Max
runtime: node v22.13.0 (arm64-darwin)

benchmark           time (avg)             (min … max)       p75       p99      p999
------------------------------------------------------ -----------------------------
• z.disriminatedUnion().parse
------------------------------------------------------ -----------------------------
zod 3           33'996 ns/iter    (31'625 ns … 321 µs) 32'416 ns    129 µs    189 µs
zod 4 (after)    9'528 ns/iter     (9'000 ns … 223 µs)  9'209 ns 10'083 ns    117 µs
zod 4 (before)  19'161 ns/iter    (18'291 ns … 207 µs) 18'584 ns 32'542 ns    128 µs

summary for z.discriminatedUnion().parse
  zod 4 (after)
   2.01x faster than zod 4 (before)
   3.57x faster than zod 3

@colinhacks colinhacks changed the title better disc union Improve discriminated union implementation May 28, 2025
@colinhacks colinhacks merged commit fe75806 into main May 28, 2025
2 of 4 checks passed
@colinhacks colinhacks deleted the better-disc-union branch May 28, 2025 23:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant