Skip to content
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

Improvement: ZodError performance impact #3878

Open
mysuf opened this issue Dec 2, 2024 · 0 comments
Open

Improvement: ZodError performance impact #3878

mysuf opened this issue Dec 2, 2024 · 0 comments

Comments

@mysuf
Copy link

mysuf commented Dec 2, 2024

Removing ZodError inheritance from the Error class doubles or even triples the op/sec for invalid benchmark tests. This is because a stack trace doesn't need to be collected, which is useless for parse errors anyway. It is pretty easy-to-do modification. The only con is that it breaks compatibility e.g. result.error instanceof Error which is somehow weird so I think it is worth it.

Invalid Tests Error Subclass (instanceof Error) Standalone Class
z.enum: invalid 131,440 ops/sec 250,984 ops/sec
long z.enum: invalid 118,232 ops/sec 224,574 ops/sec
z.undefined: invalid 127,715 ops/sec 260,896 ops/sec
z.literal: invalid 125,889 ops/sec 252,896 ops/sec
z.number: invalid type 122,146 ops/sec 259,295 ops/sec
z.number: invalid number 125,977 ops/sec 266,057 ops/sec
z.date: invalid 124,918 ops/sec 255,595 ops/sec
z.date: invalid min 123,008 ops/sec 249,733 ops/sec
z.date: invalid max 123,179 ops/sec 248,390 ops/sec
z.symbol: invalid 143,278 ops/sec 349,873 ops/sec
z.string: invalid: null 142,573 ops/sec 344,606 ops/sec
z.object: empty: invalid: null 141,122 ops/sec 346,413 ops/sec
z.object: short: invalid: null 141,898 ops/sec 346,534 ops/sec
z.object: long: invalid: null 136,760 ops/sec 347,982 ops/sec

Another +10% op/sec (V8 optimizations) on invalids just by changing handleResult's:

{
        success: false,
        get error() {
            if (this._error)
                return this._error;
            const error = new ZodError(ctx.common.issues);
            this._error = error;
            return this._error;
        },
}

to

return {
        success: false,
        error: new ZodError(ctx.common.issues)
};

Btw I'm showing just weak spots. Not proposal code.

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

No branches or pull requests

1 participant