string.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import Benchmark from "benchmark";
  2. import { z } from "zod/v3";
  3. const SUITE_NAME = "z.string";
  4. const suite = new Benchmark.Suite(SUITE_NAME);
  5. const empty = "";
  6. const short = "short";
  7. const long = "long".repeat(256);
  8. const manual = (str) => {
  9. if (typeof str !== "string") {
  10. throw new Error("Not a string");
  11. }
  12. return str;
  13. };
  14. const stringSchema = z.string();
  15. const optionalStringSchema = z.string().optional();
  16. const optionalNullableStringSchema = z.string().optional().nullable();
  17. suite
  18. .add("empty string", () => {
  19. stringSchema.parse(empty);
  20. })
  21. .add("short string", () => {
  22. stringSchema.parse(short);
  23. })
  24. .add("long string", () => {
  25. stringSchema.parse(long);
  26. })
  27. .add("optional string", () => {
  28. optionalStringSchema.parse(long);
  29. })
  30. .add("nullable string", () => {
  31. optionalNullableStringSchema.parse(long);
  32. })
  33. .add("nullable (null) string", () => {
  34. optionalNullableStringSchema.parse(null);
  35. })
  36. .add("invalid: null", () => {
  37. try {
  38. stringSchema.parse(null);
  39. }
  40. catch (_err) { }
  41. })
  42. .add("manual parser: long", () => {
  43. manual(long);
  44. })
  45. .on("cycle", (e) => {
  46. console.log(`${SUITE_NAME}: ${e.target}`);
  47. });
  48. export default {
  49. suites: [suite],
  50. };