Skip to content

Improve the performance of z.nativeEnum #4341

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
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

sluukkonen
Copy link

@sluukkonen sluukkonen commented May 9, 2025

The previous implementation converted the enum into an array of values on each parse call, even though the array was never used in the happy path.

This was especially problematic on large enums, since the work done was proportional to the size of the enum.

I also removed an extra call to util.objectValues on the failure path, since it seemed to be superfluous (util.getValidEnumValues already calls it).

Before:

z.nativeEnum: valid x 4,376,561 ops/sec ±0.65% (95 runs sampled)
z.nativeEnum: invalid x 139,663 ops/sec ±6.37% (91 runs sampled)
long z.nativeEnum: valid x 1,197,450 ops/sec ±0.25% (97 runs sampled)
long z.nativeEnum: invalid x 116,181 ops/sec ±0.46% (96 runs sampled)

After:

z.nativeEnum: valid x 10,978,553 ops/sec ±0.41% (98 runs sampled)
z.nativeEnum: invalid x 143,931 ops/sec ±5.40% (93 runs sampled)
long z.nativeEnum: valid x 9,783,582 ops/sec ±0.38% (99 runs sampled)
long z.nativeEnum: invalid x 122,292 ops/sec ±0.48% (99 runs sampled

Summary by CodeRabbit

  • New Features

    • Added new benchmark suites to measure performance of native enum schema parsing, including tests for both short and long enums with valid and invalid inputs.
  • Refactor

    • Improved internal handling of enum value retrieval for schema parsing, resulting in more direct value checks without caching in local variables. No changes to public interfaces.

Copy link

netlify bot commented May 9, 2025

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit ded6dd3
🔍 Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/681de3bf2c43a3000848ce06
😎 Deploy Preview https://deploy-preview-4341--guileless-rolypoly-866f8a.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

coderabbitai bot commented May 9, 2025

Walkthrough

This update adds two new benchmark suites for native enum parsing to both Deno and source benchmark files. It also tweaks the internal implementation of the ZodNativeEnum class by removing a local variable that cached valid enum values, opting for direct utility calls instead. No public APIs are changed.

Changes

File(s) Change Summary
deno/lib/benchmarks/primitives.ts, src/benchmarks/primitives.ts Added nativeEnumSuite and longNativeEnumSuite for benchmarking native enum parsing; included them in exports.
deno/lib/types.ts, src/types.ts Removed local caching of valid enum values in ZodNativeEnum._parse; now directly calls utility function at each use.

Sequence Diagram(s)

sequenceDiagram
    participant BenchmarkSuite
    participant ZodNativeEnum
    participant Util

    BenchmarkSuite->>ZodNativeEnum: parse(input)
    ZodNativeEnum->>Util: getValidEnumValues(enumDef)
    Util-->>ZodNativeEnum: validValues
    ZodNativeEnum->>ZodNativeEnum: check input against validValues
    ZodNativeEnum-->>BenchmarkSuite: result (success or error)
Loading

Poem

Two new suites join the race,
Native enums now set the pace.
No more caching on the side,
Utility calls take the ride.
Benchmarks run, results in tow—
Enum parsing, watch it go!
🚀

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8c7b5db and ded6dd3.

📒 Files selected for processing (4)
  • deno/lib/benchmarks/primitives.ts (2 hunks)
  • deno/lib/types.ts (2 hunks)
  • src/benchmarks/primitives.ts (2 hunks)
  • src/types.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test with Deno v1.x
🔇 Additional comments (11)
src/benchmarks/primitives.ts (3)

58-88: New benchmark suite added for z.nativeEnum

Nice addition of benchmark suites for native enum parsing! This matches the PR's goal of improving the performance of z.nativeEnum.


74-88: Additional benchmarks for large native enums

Adding specific benchmark for large enums is super helpful for validating performance improvements, especially since the PR summary mentioned that the optimization is particularly impactful for large enums.


199-200: Updated exports to include new benchmark suites

Properly added the new benchmark suites to the exported suite list. This ensures the new benchmarks will be run along with the existing ones.

deno/lib/types.ts (3)

4464-4494: Optimized ZodNativeEnum._parse method by removing unnecessary cached values

This is the key performance improvement! You've eliminated the local variable that was previously storing the result of util.getValidEnumValues(this._def.values) on every parse call. Instead, you're now calling the function directly only when needed.

By avoiding the array creation on the successful parsing path (which is the most common), you've significantly improved performance, especially for large enums.


4466-4476: Streamlined error handling for invalid types

Nice cleanup of the error handling path too - directly using util.getValidEnumValues instead of a cached variable keeps the code simpler.


4483-4485: Improved error handling for invalid enum values

Continuing the pattern - removed the cached variable here too and directly used util.getValidEnumValues. This prevents duplicated work since util.getValidEnumValues was already doing what was needed.

src/types.ts (2)

4465-4469: Nice performance optimization here! 👍

You removed the local variable that cached the results of util.getValidEnumValues and instead directly call the function when needed. This avoids unnecessary array conversion on every parse call, which is especially helpful for large enums.


4484-4485: Consistent with the pattern of direct access

Same approach here - directly calling util.getValidEnumValues instead of using a cached array. This keeps the code consistent with the change above and avoids redundant processing.

deno/lib/benchmarks/primitives.ts (3)

58-72: Good addition of benchmarks for nativeEnum

Adding dedicated benchmarks for z.nativeEnum makes sense to measure the performance impact of your implementation changes. The structure mirrors the existing enum benchmarks which helps with comparison.


74-88: Smart to test with large enum values too

Testing with both regular and large enum values is especially important since the performance improvement should be more noticeable with larger enums. This benchmark will help validate that claim in the PR description.


199-200: Don't forget to include the new benchmarks

Good job adding the new benchmark suites to the exported suites array - this ensures they'll be run as part of the benchmark suite.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

sluukkonen added 2 commits May 9, 2025 14:14
The previous implementation converted the enum into an array of values
on each parse call, even though the array was never used in the happy
path.

This was especially problematic on large enums, since the work done was
proportional to the size of the enum.

I also removed an extra call to `util.objectValues` on the failure path,
since it seemed to be superfluous (`util.getValidEnumValues` already
calls it).

Before:

    z.nativeEnum: valid x 4,376,561 ops/sec ±0.65% (95 runs sampled)
    z.nativeEnum: invalid x 139,663 ops/sec ±6.37% (91 runs sampled)
    long z.nativeEnum: valid x 1,197,450 ops/sec ±0.25% (97 runs sampled)
    long z.nativeEnum: invalid x 116,181 ops/sec ±0.46% (96 runs sampled)

After

    z.nativeEnum: valid x 10,978,553 ops/sec ±0.41% (98 runs sampled)
    z.nativeEnum: invalid x 143,931 ops/sec ±5.40% (93 runs sampled)
    long z.nativeEnum: valid x 9,783,582 ops/sec ±0.38% (99 runs sampled)
    long z.nativeEnum: invalid x 122,292 ops/sec ±0.48% (99 runs sampled)
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