Skip to content

Load protodef-validator only when validation is requested - #174

Closed
u9g wants to merge 1 commit into
ProtoDef-io:masterfrom
u9g:lazy-validator
Closed

Load protodef-validator only when validation is requested#174
u9g wants to merge 1 commit into
ProtoDef-io:masterfrom
u9g:lazy-validator

Conversation

@u9g

@u9g u9g commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

Problem

require('protodef') loads protodef-validator and its ajv dependency tree for every consumer, even ones that never validate (e.g. node-minecraft-protocol's serializer uses new ProtoDef(false)). Profiling require('mineflayer') with a Module._load hook shows the validator+ajv subtree costs ~19ms warm — noticeably more with a cold file cache — out of a ~140ms warm require.

Two eager load points:

  • src/protodef.js requires the validator at the top of the module, unconditionally.
  • src/index.js constructs a module-scope new ProtoDef() (validation defaults on) just to export the default types, so even the lazy require would still fire for everyone.

Change

  • Move the require into the constructor's validation ? ... : null branch, so it loads on first validated construction.
  • Build the types-export instance with validation off — the validator only validates, it never affects the constructed types.

Validation behavior when requested is unchanged: new ProtoDef(true) (the default) still constructs a working validator.

Verification

  • npm test: 497 passing, standard clean.
  • After the change, require('protodef') no longer has protodef-validator in require.cache; new ProtoDef(true) still does.

require('protodef') was paying for protodef-validator and its ajv
dependency tree (~19ms warm, more cold) even for consumers that never
validate: the top-level require in protodef.js loaded it
unconditionally, and the module-scope ProtoDef() in index.js (which
only exists to export the default types) constructed a validator
eagerly on top.

Move the require into the constructor's validation branch and build the
types-export instance with validation off. Validation behavior when
requested is unchanged; the validator simply loads on first use.
@u9g u9g closed this Aug 30, 2026
@u9g

u9g commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

19ms…

@u9g
u9g deleted the lazy-validator branch August 30, 2026 21:26
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.

1 participant