Skip to content

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