Skip to content

Conversation

@jmike
Copy link
Contributor

@jmike jmike commented Aug 15, 2023

Improve zod's performance by using Set.has instead of Array.indexOf when checking for the presence of a value inside ZodEnum or ZodNativeEnum.

Array.indexOf is especially problematic when passing multiple (e.g. 30+) values to an enum. This PR introduces a very simple change that turns an O(n) operation to O(1).

Benchmarks

Before this PR

benchmark-results-latest-master

After this PR

benchmark-results-using-set

Conclusions

  • Using Set.has we were able to increase the performance of the parse method in ZodEnum and ZodNativeEnum by 20%.
  • The more the enum values the greater the benefit by using Set instead of Array.

@netlify
Copy link

netlify bot commented Aug 15, 2023

Deploy Preview for guileless-rolypoly-866f8a ready!

Name Link
🔨 Latest commit fd363f3
🔍 Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/661ee2cb721c940008a08a04
😎 Deploy Preview https://deploy-preview-2659--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.

@colinhacks colinhacks force-pushed the feat-use-set-for-enum-comparison branch from 24b8348 to fd363f3 Compare April 16, 2024 20:42
@colinhacks
Copy link
Owner

Thanks this is excellent! I switched to the #cache approach primarily to avoid including valueSet in the def. The def should be the minimum set of runtime information required to instantiate the schema, ideally with no redundancy. Thanks again!

@colinhacks colinhacks merged commit dae761d into colinhacks:master Apr 16, 2024
@colinhacks colinhacks mentioned this pull request Apr 21, 2024
@colinhacks
Copy link
Owner

This has landed in Zod 3.23.

https://github.com/colinhacks/zod/releases/tag/v3.23.0

@jmike jmike deleted the feat-use-set-for-enum-comparison branch April 22, 2024 06:44
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.

2 participants