r/javascript • • Jun 11 '26

Compile Zod schemas into zero-overhead validators (2-74x faster)

https://github.com/gajus/zod-compiler
47 Upvotes

18 comments sorted by

6

u/Akkuma Jun 11 '26

How does this compare in performance to using https://github.com/sinclairzx81/typedriver ?

4

u/gajus0 Jun 11 '26

No clue, but...

  • the goal was to compile Zod schemas not to invent new API

  • considering that zod-compiler inlines validation logic, it's highly unlikely that anything would be faster

There are actually a few things that are happening behind the scenes. Best illustrated with an example.

import { pool, sql } from "./db.js";
import { z } from "zod";

const getUser = (id: number) => {
  return pool.one(
    sql.type(
      z.object({
        id: z.number(),
        name: z.string(),
      }),
    )`SELECT id, name FROM users WHERE id = ${id}`,
  );
};

In this example, there are a few overheads:

  1. z.object() initialization

  2. data validation using Zod parser

This plugin transpiles your build to turn it into:

import { __zcFin, __zcFinD, __zcIT, __zcMkv } from "virtual:zod-compiler/runtime";
const _zh_6c9cb1a3 = /* @__PURE__ */ (() => {
  function __fc_0(input) {
    return (
      typeof input === "object" &&
      input !== null &&
      !Array.isArray(input) &&
      Number.isFinite(input["id"]) &&
      typeof input["name"] === "string"
    );
  }
  function __sw_2(input) {
    var _e = [];
    /* error-collecting walk — runs only when .error is read */ return _e;
  }
  function safeParse__zh_6c9cb1a3(input) {
    if (__fc_0(input)) {
      return { success: true, data: input };
    }
    return __zcFinD(__sw_2, input);
  }
  return __zcMkv(
    safeParse__zh_6c9cb1a3,
    z.object({
      id: z.number(),
      name: z.string(),
    }),
    __fc_0,
  );
})();
import { pool, sql } from "./db.js";
import { z } from "zod";

const getUser = (id: number) => {
  return pool.one(sql.type(_zh_6c9cb1a3)`SELECT id, name FROM users WHERE id = ${id}`);
};

Here:

  1. initialization is hoisted (skipping the entire re-initialization)

  2. the entire zod parser is dropped in favor of inlined validation logic

This dramatically reduces how many hops JavaScript engine needs to go through when validating your data.

0

u/gajus0 Jun 11 '26

There is a benchmark that compares zod-compiler against zod v3, v4, typia, and Ajv, https://github.com/gajus/zod-compiler#benchmark

→ More replies (1)

4

u/microbiont Jun 11 '26

Zod 4 uses JIT / Function() constructors, so I'd be surprised if you're getting speedup from AOT with significantly more than two runs. Are you also including the hoisting speedup in the 2-74x number?

I haven't looked at your code, but even if there were no speedup, AOT is nice because you don't have that first Function() constructor call and you can run with a stricter CSP.

2

u/gajus0 Jun 11 '26

Are you also including the hoisting speedup in the 2-74x number?

Nope. That would be a lot more than 2-74x improvement.

https://github.com/gajus/babel-plugin-zod-hoist#motivation

3

u/microbiont Jun 11 '26

I'm aware hoisting is needed for Zod's JIT to work at all in the way you're using Zod, b ut assuming someone defines their schemas the normal way I'm still skeptical there's a significant speedup. JIT should be the same as AOT after the first run, but I'll still run my own benchmark and report back...

→ More replies (4)

2

u/name_was_taken Jun 11 '26

Neat, but I'm trying to imagine the form that needs 74x speed improvement to the validation. It's a pretty crazy form.

Even 2x speed improvement is probably imperceptible to the user for the vast majority of forms.

23

u/gajus0 Jun 11 '26

We use Zod to validate all data that goes in/out of the application. Things like forms, URL parameters, HTTP responses, SQL responses, etc.

You can see an example in the context of PostgreSQL here https://github.com/gajus/slonik

so even a marginal improvement to Zod performance is a win, but.. 2-74x improvement just helped us to scale down quite a few replicas.

After adopting zod-compiler validation is no longer even in the top 10 of where our CPU is spending time.

9

u/mohamed_am83 Jun 11 '26

Zod is not just for validating forms. I once implemented event sourcing with Kafka with zod schemas validation. When you process thousands of events every day, such speedup makes a difference.

1

u/Rustywolf Jun 12 '26

Pretty easy to see why it matters once you consider validation for json data via api

1

u/mattsowa Jun 11 '26

Would love the same for valibot

1

u/servermeta_net Jun 11 '26

Even better would be to write parsers with validation from Json schemas