Skip to content

Conversation

jacopobonomi
Copy link

This PR improves schema initialization performance by (~5-15%) by deferring the creation of the "~standard" property until it's actually accessed.

Problem

The ~standard property implements the https://github.com/standard-schema/standard-schema but is rarely used in typical applications. Currently, this object is created eagerly for every schema during initialization, adding unnecessary overhead:

  inst["~standard"] = {
    validate: (value: unknown) => { ... },
    vendor: "zod",
    version: 1 as const,
  };

Solution

Convert the property to a lazy getter that only creates the object when accessed, then caches the result:

  Object.defineProperty(inst, "~standard", {
    get() {
      const standardSchema = {
        validate: (value: unknown) => { ... },
        vendor: "zod",
        version: 1 as const,
      };
      // Cache the result after first access
      Object.defineProperty(this, "~standard", {
        value: standardSchema,
        writable: false,
        enumerable: false,
        configurable: false,
      });
      return standardSchema;
    },
    enumerable: false,
    configurable: true,
  });

@colinhacks
Copy link
Owner

Great idea. I appreciate you looking into the initialization perf. How are you benchmarking that? I'd like to have a decent benchmark for initialization if you have one - feel free to add it under /packages/bench.

General approach is good. This same pattern is already implemented as util.cached in the utils.ts file. Try using that function instead.

@colinhacks colinhacks requested a review from Copilot October 21, 2025 17:26
Repository owner deleted a comment from coderabbitai bot Oct 21, 2025
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR optimizes schema initialization performance by converting the ~standard property from eager initialization to lazy loading with caching. The Standard Schema protocol support object is now only created when accessed, reducing unnecessary overhead for applications that don't use this feature.

Key Changes:

  • Converted ~standard property to a lazy getter using Object.defineProperty
  • Added caching mechanism to store the result after first access
  • Reformatted the async fallback in the validate function for better readability

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

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