Improve the performance of z.nativeEnum
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
With an enum containing 500 members, the difference is about 2000 times larger.
Before:
really long z.nativeEnum: valid x 4,583 ops/sec ±12.75% (86 runs sampled)
really long z.nativeEnum: invalid x 4,197 ops/sec ±2.06% (91 runs sampled)
After:
really long z.nativeEnum: valid x 9,444,581 ops/sec ±0.29% (99 runs sampled)
really long z.nativeEnum: invalid x 4,570 ops/sec ±0.89% (95 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.
Deploy Preview for guileless-rolypoly-866f8a ready!
Built without sensitive environment variables
| Name | Link |
|---|---|
| Latest commit | ded6dd3a8b668793f827ed6e61725c1bc2a4a3df |
| 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...Use your smartphone camera to open QR code link. |
To edit notification comments on pull requests, go to your Netlify site configuration.
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)
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 Cacheat either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off theData Retentionsetting 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 8c7b5db005096a72f45c6bacabcb453605e07726 and ded6dd3a8b668793f827ed6e61725c1bc2a4a3df.
📒 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 forz.nativeEnumNice 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 enumsAdding 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 suitesProperly 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: OptimizedZodNativeEnum._parsemethod by removing unnecessary cached valuesThis 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 typesNice cleanup of the error handling path too - directly using
util.getValidEnumValuesinstead of a cached variable keeps the code simpler.
4483-4485: Improved error handling for invalid enum valuesContinuing the pattern - removed the cached variable here too and directly used
util.getValidEnumValues. This prevents duplicated work sinceutil.getValidEnumValueswas 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.getValidEnumValuesand 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 accessSame approach here - directly calling
util.getValidEnumValuesinstead 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 fornativeEnumAdding dedicated benchmarks for
z.nativeEnummakes 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 tooTesting 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 benchmarksGood 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
@coderabbitaiin 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
@coderabbitaiin 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 pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger an incremental review. This is useful when automatic reviews are disabled for the repository.@coderabbitai full reviewto do a full review from scratch and review all the files again.@coderabbitai summaryto regenerate the summary of the PR.@coderabbitai generate docstringsto generate docstrings for this PR.@coderabbitai generate sequence diagramto generate a sequence diagram of the changes in this PR.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai configurationto show the current CodeRabbit configuration for the repository.@coderabbitai helpto get help.
Other keywords and placeholders
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere in the PR title to generate the title automatically.
CodeRabbit Configuration File (.coderabbit.yaml)
- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile 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 Is this still relevant in the v4 code path?
@sluukkonen Is this still relevant in the v4 code path?
I’m not sure, I haven’t looked at v4 too closely yet. Hopefully not.