If you've used NestJS, a Megh DTO looks familiar:

import { IsString, MinLength, MaxLength, IsOptional, IsBoolean, IsIn } from '@meghjs/core'; export class CreateTodoDto { @IsString() @MinLength(1) @MaxLength(200) title: string; @IsOptional() @IsBoolean() completed?: boolean; @IsOptional() @IsIn(['low', 'medium', 'high']) priority?: 'low' | 'medium' | 'high'; } 

These are class-validator's decorators, with the same names, options and
error messages, but they're imported from @meghjs/core. Megh also still
accepts DTOs written with class-validator itself.

So why write a second implementation of a library that already works? This
post explains the problem, shows the code Megh generates, and gives you a
benchmark you can run yourself.

class-validator is good, but it repeats itself

class-validator and
class-transformer are the
standard way to validate DTOs in TypeScript. They're mature, well tested and
widely known, and that's exactly why Megh copies their API.

The cost is in how they run. On every validated request:

  1. class-transformer walks the body and builds a class instance from it (plainToInstance).
  2. class-validator reads the decorator metadata stored for that class, groups it by property, and loops over every property and every rule. Each rule is looked up and run through a general-purpose executor.
  3. For each failing rule, it builds the error message by filling a template with string replacements.

None of that changes between requests. Your rules are fixed when the app
starts, yet steps 1–3 run again for every request.

That adds up. In Megh's HTTP benchmark (in the repo under benchmarks/), a
route with a 3-field class-validator body ran at about 55% of raw Fastify's
throughput
, while routes without a body kept about 90%. Nearly all of that
difference was spent in class-validator and class-transformer. NestJS lands
at about the same number because it uses the same libraries.

Compile once, then just call a function

Fastify solved the same problem for JSON Schema long ago. ajv turns a schema
into JavaScript source once, and validating is then a plain function call.

Megh does the same for DTOs. The first time a DTO is validated, Megh reads
its decorators and generates one JavaScript function that checks exactly
that DTO's properties, then caches it. Every request after that just calls the
function.

Here is the actual function Megh generates for CreateTodoDto above,
captured from a running app:

"use strict"; var k0 = R[0].constraints, p0 = P[0], f0 = R[0].check.fn; var k1 = R[1].constraints, p1 = P[1], f1 = R[1].check.fn; var k2 = R[2].constraints, p2 = P[2], f2 = R[2].check.fn; var f3 = R[3].condition; var k4 = R[4].constraints, p4 = P[4], f4 = R[4].check.fn; var f5 = R[5].condition; var k6 = R[6].constraints, p6 = P[6], f6 = R[6].check.fn; return function check(o, errs, prefix) { var keys = Object.keys(o), i, k, v, c, ok, okEach, it; for (i = 0; i < keys.length; i++) { k = keys[i]; if (!A.has(k)) errs.push({ path: prefix + k, constraints: { whitelistValidation: "property " + k + " should not exist" } }); } v = o["title"]; ok = true; if (ok) { c = undefined; if (!(typeof v === "string" && H.isLength(v, 0, k0[0]))) (c || (c = {}))["maxLength"] = H.message(R[0], o, v); if (!(typeof v === "string" && H.isLength(v, k1[0], undefined))) (c || (c = {}))["minLength"] = H.message(R[1], o, v); if (!(typeof v === "string" || v instanceof String)) (c || (c = {}))["isString"] = H.message(R[2], o, v); if (c !== undefined) errs.push({ path: prefix + "title", constraints: c }); } v = o["completed"]; ok = true; if (!f3(o, v)) ok = false; if (ok) { c = undefined; if (!(typeof v === "boolean" || v instanceof Boolean)) (c || (c = {}))["isBoolean"] = H.message(R[4], o, v); if (c !== undefined) errs.push({ path: prefix + "completed", constraints: c }); } v = o["priority"]; ok = true; if (!f5(o, v)) ok = false; if (ok) { c = undefined; if (!(Array.isArray(k6[0]) && k6[0].indexOf(v) !== -1)) (c || (c = {}))["isIn"] = H.message(R[6], o, v); if (c !== undefined) errs.push({ path: prefix + "priority", constraints: c }); } }; 

What to notice:

  • Unknown properties are checked first, in one pass. Any key that isn't on the DTO (an isAdmin a client tried to slip in) becomes a whitelistValidation error. This is class-validator's whitelist + forbidNonWhitelisted behavior, built in.
  • Common checks are inlined. @IsString() becomes typeof v === "string", and @IsIn([...]) becomes an indexOf. There's no rule lookup and no executor in between.
  • @IsOptional() skips the rest. The f3 / f5 conditions stop checking completed and priority when they're absent.
  • Messages are built only when a check fails. A valid body never touches a message template, which is why valid bodies get the biggest speed-up.
  • Only property names and rule numbers are written into the source. Constraint values, messages and your own @Transform functions are passed in by reference (R, P, H), never pasted into code as text. That keeps the code generation safe from injection through DTO metadata.

The numbers

Here's the benchmark: the same DTO defined twice, once with Megh's decorators
and once with class-validator's. The class-validator side uses the standard
plainToInstance + validateSync with whitelist and
forbidNonWhitelisted, which is what NestJS and Megh run per request.

// src/bench/validate.bench.ts import 'reflect-metadata'; import * as megh from '@meghjs/core'; import * as cv from 'class-validator'; import { plainToInstance } from 'class-transformer'; const PRIORITIES = ['low', 'medium', 'high']; // The same DTO twice: once with Megh's decorators... class MeghTodoDto { @megh.IsString() @megh.MinLength(1) @megh.MaxLength(200) title: string; @megh.IsOptional() @megh.IsBoolean() completed?: boolean; @megh.IsOptional() @megh.IsIn(PRIORITIES) priority?: string; } // ...and once with class-validator's. class CvTodoDto { @cv.IsString() @cv.MinLength(1) @cv.MaxLength(200) title: string; @cv.IsOptional() @cv.IsBoolean() completed?: boolean; @cv.IsOptional() @cv.IsIn(PRIORITIES) priority?: string; } const validateWithMegh = (body: object) => megh.validateDto(MeghTodoDto, body).errors ?? []; const validateWithCv = (body: object) => cv.validateSync(plainToInstance(CvTodoDto, body), { whitelist: true, forbidNonWhitelisted: true }); const valid = { title: 'Buy milk', completed: false, priority: 'high' }; const invalid = { title: '', priority: 'urgent', isAdmin: true }; // Same verdicts first, or the timings mean nothing. console.log('errors, valid body: megh', validateWithMegh(valid).length, '| class-validator', validateWithCv(valid).length); console.log('errors, invalid body: megh', validateWithMegh(invalid).length, '| class-validator', validateWithCv(invalid).length); function time(label: string, fn: () => unknown, n = 200_000): number { for (let i = 0; i < 20_000; i++) fn(); // warm up const start = process.hrtime.bigint(); for (let i = 0; i < n; i++) fn(); const us = Number(process.hrtime.bigint() - start) / 1000 / n; console.log(` ${label.padEnd(24)} ${us.toFixed(2)} µs`); return us; } for (let run = 1; run <= 3; run++) { console.log(`run ${run}`); const a = time('class-validator, valid', () => validateWithCv(valid)); const b = time('megh, valid', () => validateWithMegh(valid)); const c = time('class-validator, invalid', () => validateWithCv(invalid)); const d = time('megh, invalid', () => validateWithMegh(invalid)); console.log(` speed-up: valid ${(a / b).toFixed(1)}x, invalid ${(c / d).toFixed(1)}x`); } 

Both libraries agree before any timing starts: 0 errors for the valid body,
3 errors for the invalid one. Results on Node 24 on a laptop (Intel
i5-11320H), median of 3 runs:

Time per validation (µs, lower is better) Valid body class-validator ███████████████ 7.25 Megh █ 0.57 ~13× faster Invalid body (3 errors) class-validator ██████████████████████ 11.06 Megh ██████ 2.96 ~4× faster 
Payload class-validator + class-transformer Megh Speed-up
Valid body 7.21 – 7.37 µs 0.54 – 0.67 µs 11–13×
Invalid body (3 errors) 11.03 – 11.21 µs 2.74 – 3.00 µs ~4×

The gap is smaller for invalid bodies because both sides then do the same
unavoidable work: building three error objects and three messages.

Run it yourself. In any Megh project (npx @meghjs/cli new bench-app),
save the file as src/bench/validate.bench.ts, then:

npx tsc -p tsconfig.json --outDir dist-bench node dist-bench/bench/validate.bench.js 

Your absolute numbers will differ, but the ratios should be close.

A note on scope. These are per-call numbers, in process. A full HTTP
request also pays for routing, body parsing and serialization, so the
requests-per-second gain on a real route is smaller than 13×. What changes
is that validation stops being the biggest cost on the route.

What you get besides speed

Switching is just an import change. The decorator names, options,
constraint keys and default messages all match:

import { IsString, MinLength } from 'class-validator'; // before import { Type } from 'class-transformer'; // before import { IsString, MinLength, Type } from '@meghjs/core'; // after 

Error responses, the values your handler receives and the generated OpenAPI
schema stay the same. Megh's test suite checks this against class-validator
with hand-picked cases and seeded random payloads.

Mixing libraries fails loudly at startup. If one DTO uses Megh decorators
for some fields and class-validator decorators for others, each library would
check only its own rules, and some rules would be silently skipped. Megh
refuses to start instead.

One definition does three jobs. The same decorators validate the request,
convert input (?page=2 arrives as the number 2), and produce the OpenAPI
schema for your /docs page.

Fewer surprises in edge cases. @IsEmail() with default options is checked
by Megh directly. In Megh's tests it gives the same answers as the validator
package, about 9× faster. It also rejects addresses with an unpaired UTF-16
surrogate cleanly, a case where the validator package throws a URIError
that would otherwise become a 500.

When to keep class-validator

Megh's validator covers the common decorators, but not everything yet. Keep a
DTO on class-validator if it needs:

  • custom validators: @Validate, @ValidatorConstraint, registerDecorator
  • @Expose, @Exclude, or @Type with a discriminator
  • a class-validator decorator Megh doesn't have yet (the validation docs list what's supported)

Those DTOs keep working unchanged. You can also try an experimental option
that compiles class-validator DTOs from class-validator's own metadata:

const app = Megh.createApplication({ experimental: { compiledValidation: true }, }); 

(or set MEGH_COMPILED_VALIDATION=1). It gives the same results. Any DTO it
can't reproduce exactly (nested DTOs, @Type, @Transform, async validators)
falls back to class-validator as before. Being experimental, this option may
change in a minor release.

Summary

  • class-validator is the right API, so Megh kept it.
  • Re-reading the same rules on every request is the wrong execution model for a server's hottest path, so Megh changed that part.
  • The result is the same DTOs, errors and docs, with validation about 13× faster for valid input and 4× for invalid input.

New to Megh? Start with Meet Megh: build a validated Todo REST API.

Docs: https://meghjs.github.io · Source: https://github.com/meghjs/megh