Skip to content

Reuse one Jinjava engine per renderer instead of building one per render - #145

Merged
alexheifetz merged 1 commit into
mainfrom
perf/jinjava-reuse-engine
Nov 24, 2026
Merged

alexheifetz merged 1 commit into
mainfrom
perf/jinjava-reuse-engine

Conversation

@johnsonr

Copy link
Copy Markdown
Contributor

Why

JinjavaTemplateRenderer.renderLiteralTemplate built a new Jinjava on every call. Building one registers the whole library of filters, functions and tags, and on a short template that costs more than the render itself.

Found by profiling an Embabel appliance indexing 12 repositories (66,362 declarations): a realm documents source renders three literal templates per record, and SimpleLibrary.register showed up among the top self-time frames. Engine construction was 7–9% of the ingest's CPU.

The change

  • One engine per renderer, built on first use and reused.
  • A Jinjava is safe to share between threads, because each render gets its own interpreter.
  • JinjaProperties has mutable var fields, so the engine is cached against the two settings it is built from (failOnUnknownTokens, nestedInterpretationEnabled) and rebuilt if either changes. A change after construction therefore still takes effect on the next render, as it did when every render read the properties.

Measured

A one-line template, after warm-up: 74 µs → 47 µs per render (−37%). The remaining 47 µs is mostly parsing, since Jinjava re-parses the template on each render; caching parsed templates would be a separate change.

Tests

Three new tests in JinjavaTemplateRendererTest, all 29 passing:

  • a setting changed after construction takes effect on the next render;
  • a failed render leaves the next one unaffected;
  • 400 renders across 8 threads each get their own model's output.

🤖 Generated with Claude Code

renderLiteralTemplate built a new Jinjava on every call, and building one
registers its whole library of filters, functions and tags. On a short
template that construction cost more than the render: 74 us a render
before, 47 us after. A realm documents source rendering three templates
per record spent 7-9% of a 66,000-record ingest building engines.

A Jinjava is safe to share between threads (each render gets its own
interpreter). The engine is cached against the two settings it is built
from, so a change to the mutable JinjaProperties after construction still
takes effect on the next render, as it did when each render read them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alexheifetz
alexheifetz merged commit 565428a into main Nov 24, 2026
7 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