Skip to content

Format the name for $ref calls with only the loop variables it uses - #239

Merged
horejsek merged 2 commits into
horejsek:masterfrom
g4lb:perf-format-name-locals
Nov 17, 2026
Merged

horejsek merged 2 commits into
horejsek:masterfrom
g4lb:perf-format-name-locals

Conversation

@g4lb

@g4lb g4lb commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

A $ref in items, additionalItems, patternProperties or additionalProperties calls the referenced function one time for each item. To make the name for each call, the generated code uses .format(**locals()). This copies all local variables of the function on each call. Now the generated code gives only the loop variables of the path, for example .format(data_x=data_x). The output does not change.

Benchmark Before After Change
items: {$ref}, 1000 strings 419 µs 158 µs -62%
additionalProperties: {$ref}, 500 keys 224 µs 91 µs -59%
Recursive $ref tree, 511 nodes 505 µs 276 µs -45%
Draft-07 metaschema, validate itself 184 µs 122 µs -34%

The table shows CPython 3.15. CPython 3.14 gives the same results. On CPython 3.10, these rows are 22% to 32% faster.

I measured no slowdown on the performance.py schema (valid and invalid values) and on objects and arrays without $ref. I also measured no slowdown on compile() and compile_to_code() of the draft-04 and draft-07 metaschemas. compile_to_code() of a test schema that has only 150 $ref in loops is 1.5% to 2.3% slower. I used 20 to 30 interleaved rounds and a Mann-Whitney test (Apple M5, CPython 3.10, 3.14 and 3.15). I did not measure other architectures.

Tests:

  • pytest -W default --benchmark-skip passes: 4758 passed, with the same skipped, xfailed and xpassed counts as master.
  • pylint fastjsonschema gives the same warnings as master (9.90/10).
  • Old and new validators gave the same results on 1,125,786 inputs: the JSON-Schema-Test-Suite schemas, the schemas of the repository tests, and random schemas. The test compared the return values and each exception: type, message, value, name, path, definition and rule.
  • CHANGELOG.txt has an entry under UNRELEASED.

@horejsek
horejsek merged commit ac21f4c into horejsek:master Nov 17, 2026
16 checks passed
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