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
timorthi pushed a commit to timorthi/zod that referenced this pull request Jun 3, 2025
* WIP

* Simplify discriminated union logic

* Simplify disc union internals, improve perf

* Improve docs

* Typo
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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy