Skip to content

Make rendering large templates linear again - #210

Merged
cvas22 merged 1 commit into
mainfrom
perf/74-render-scaling
Nov 25, 2026
Merged

cvas22 merged 1 commit into
mainfrom
perf/74-render-scaling

Conversation

@cvas22

@cvas22 cvas22 commented Nov 25, 2026

Copy link
Copy Markdown
Owner

#74 reports 27 minutes for a template with about 12,000 variables. Profiling showed most of the render time in map_tree(), which does a single root.replace(body, tree). lxml has to move a large subtree from one document to another for that, and it takes quadratic time: detaching the template's old body costs 0.2s, 0.8s and 3.1s at 3k, 6k and 12k variables, and attaching a body with one big table is just as bad.

map_tree() now serializes the document, splices in the rendered body and parses it once with python-docx's parser, then points both the Document and its part at the new root. Nothing moves between documents anymore. If the body markers can't be found it falls back to the old replace.

Render time, same machine, one run each (Python 3.14, Windows):

template 3,000 vars 6,000 12,000
table, before 0.80s 2.34s 4.91s
table, after 0.58s 1.15s 2.30s
split runs, before 0.62s 1.69s 4.98s
split runs, after 0.43s 0.88s 2.27s

The curve is linear now; what's left is mostly Jinja compiling the template. I couldn't reproduce the full 27 minutes with generated templates, so the reporter's file may have something else going on too.

All 41 example outputs from tests/runtests.py produce byte-identical word/document.xml before and after. There's no timing test since that would be flaky in CI; the new test checks the document and its part share the rendered root and that python-docx reads see the rendered content.

Fixes #74

map_tree() replaced the body element with the rendered tree, and lxml
takes quadratic time to move a big subtree between documents. Detaching
the old body and attaching a table-heavy new one were both quadratic,
so a few thousand variables cost seconds and tens of thousands minutes.
Splice the rendered body into the document XML and parse it once, then
point the document and its part at the new root.

Fixes #74
@github-actions github-actions Bot added code Changes to the docform package tests Changes to tests labels Nov 25, 2026
@cvas22
cvas22 merged commit 6fb9182 into main Nov 25, 2026
11 checks passed
@cvas22
cvas22 deleted the perf/74-render-scaling branch November 25, 2026 17:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

code Changes to the docform package tests Changes to tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Render takes increasingly long on large number of variables

1 participant