Repository navigation
Description
Follows #389, #398, #407, #437 and #445. Each one named calls and a script, and each release made those calls local for the paragraphs of the script. This issue is about what they share, measured on public documents. v0.17.0 (main eb980e94), release wheel from PyPI, Linux x86_64.
What happens
The same edits on a public 22-page report saved by Word (796 paragraphs, document.xml 458 kB), milliseconds per call:
| Call | python-docx 1.2.0 | 0.16.0 | 0.16.4 | 0.17.0 |
|---|---|---|---|---|
Run.text |
0.03 | 0.00 | 101 | 129 |
Paragraph.text |
0.03 | 0.02 | 12 | 11 |
Paragraph.add_run |
0.02 | 0.00 | 12 | 17 |
Table.add_row |
0.11 | 192 | 225 | |
Document.remove_content |
151 | 193 | 216 | |
Paragraph.replace_xml |
213 | 269 | ||
Document.add_footnote |
98 | 125 | ||
Cell.text |
0.03 | 153 | 214 | 27 |
Paragraph.insert_paragraph_before |
0.02 | 0.7 | 0.8 | |
Document.add_paragraph |
0.03 | 0.00 | 0.2 | 0.3 |
An empty cell is a call that library or version does not have in this form.
On a public 66-page report (817 paragraphs, 48 tables, document.xml 4.3 MB) with 0.17.0: Run.text 0.78 s, Paragraph.text 0.21 s, Table.add_row 1.4 s, remove_content 1.3 s, add_footnote 1.7 s, Paragraph.replace_xml 4.3 s, and 4.1 s to open (1.0 s with 0.16.4). On the same file insert_paragraph_before costs 2.2 ms and Cell.text 0.8 ms.
So the local routes work, and every call outside them costs the body. An agent that rewrites 200 runs of the 66-page report waits 2.6 minutes.
The two files (Open Government Licence):
- 22 pages: https://assets.publishing.service.gov.uk/media/5a7bfac7ed915d4147622056/Classifying_and_Measuring_the_Creative_Industries_Consultation_Paper_April_2013-final.docx, SHA-256
98f2c9b64a5c02ad6502f11e94d2990241c9c9ab31c6b67a476967c9dabf9336 - 66 pages: https://assets.publishing.service.gov.uk/media/5e18828eed915d3b07ed038d/Interim_Evalution_of_the_Taylor_Review_Pilot__Word_.docx, SHA-256
e6e71ef68d8f5aa53962273f3eb03324b51d563f37f00f544117254fffcbfb36
Why
Read in the source and counted with callgrind on hadim/rdocx 2543cf63 (v0.17.0 plus #448 to #452 and #454):
- A saved paragraph is never plain. The local routes ask for a plain paragraph (
paragraph_is_plain, behindplain_removable_paragraph,plain_direct_paragraphanddirect_body_paragraph_facts). Word and Google Docs writew:rsid*andw14:paraIdon their paragraphs, which are kept as retained markup, so the paragraph is not plain: in the script belowremove_contentof a paragraph costs 0.2 ms in the body as rdocx writes it and 67 ms in the saved one. Every paragraph of the four public documents we measured carries them. - The fallback walks the whole body many times in one call. On a body of 100 paragraphs as Google Docs saves list items (identity attributes, its paragraph and run properties, one tab stop each), one
remove_contentserializes each block alone 23 times and parses it 6 times. 86 % of that call is intry_remove_content:canonicalize_all_drawing_idstakes 31 % of the call with no drawing in the document,reconcile_comment_removal15 % with no comment. OneRun.textserializes each block 18 times, with 82 % of the call insaves_as(96 % on the 22-page file). OneParagraph.textreads the owner facts of each block twice. - A block with a field, a bookmark or a tab stop is parsed again at each read, and its owner facts are read again at each publication (
owner_facts_reusable_by_value, F-X268). The headings of a document with a table of contents hold a bookmark, and its entries a tab stop and a field.
Script
It builds its own input, prints PASS or FAIL per call and exits 1 while a call fails. Two calls that are already local are in it as controls.
case1_saved_body.py
"""Case 1: an edit costs the whole body when the document holds what Word and Google Docs save.
Builds its own input: bodies of N paragraphs of two runs with one 6 x 3 table, written two ways. "As rdocx writes
it" holds the text alone. "As saved" holds the same text with what Word and Google Docs write: w:rsid* on every
paragraph and run, w14:paraId on every paragraph, a bookmark on one paragraph in ten (the headings of a document
with a table of contents) and a tab stop on one in ten. No timed call touches a paragraph that holds a bookmark or
a tab stop.
Each call is timed on three targets of a document opened for it, the median counting. PASS when the call costs at
most 1.5 times as much in the saved body of 400 paragraphs as in the saved body of 100, plus 1 ms. The cost in the
body of 400 as rdocx writes it is printed beside it. Exits 1 while a call fails.
"""
import io
import platform
import statistics
import sys
import time
import zipfile
from importlib.metadata import version
import rdocx
print(f"rdocx {version('rdocx')}, Python {platform.python_version()}, {platform.system()} {platform.machine()}")
SMALL, LARGE = 100, 400
W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
W14 = "http://schemas.microsoft.com/office/word/2010/wordml"
CONTENT_TYPES = (
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
'<Default Extension="xml" ContentType="application/xml"/>'
'<Override PartName="/word/document.xml" ContentType='
'"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>'
)
RELATIONSHIPS = (
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" '
'Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" '
'Target="word/document.xml"/></Relationships>'
)
def paragraph(index, saved, texts):
"""One paragraph of one run per text. Body paragraph `index` holds a tab stop or a bookmark one time in ten."""
identity = f' w:rsidR="00A31F2C" w:rsidRDefault="00A31F2C" w14:paraId="{index + 1:08X}"' if saved else ""
run = ' w:rsidRPr="00B7440E"' if saved else ""
tab_stop = '<w:pPr><w:tabs><w:tab w:val="left" w:pos="720"/></w:tabs></w:pPr>' if saved and index % 10 == 1 else ""
runs = "".join(f'<w:r{run}><w:t xml:space="preserve">{text}</w:t></w:r>' for text in texts)
if saved and index % 10 == 2:
runs = f'<w:bookmarkStart w:id="{index}" w:name="_Toc{index}"/>{runs}<w:bookmarkEnd w:id="{index}"/>'
return f"<w:p{identity}>{tab_stop}{runs}</w:p>"
def table(saved):
cells = [f'<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr>{paragraph(10000 + 10 * k, saved, [f"cell {k}"])}'
"</w:tc>" for k in range(18)]
rows = "".join("<w:tr>" + "".join(cells[3 * row:3 * row + 3]) + "</w:tr>" for row in range(6))
return ('<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/></w:tblPr><w:tblGrid>' + '<w:gridCol w:w="2000"/>' * 3
+ f"</w:tblGrid>{rows}</w:tbl>")
def package(count, saved):
blocks = [paragraph(k, saved, [f"Paragraph {k} first run. ", "second run."]) for k in range(count)]
blocks.insert(count // 4, table(saved)) # body index of paragraph k: k + 1 from count // 4 on
document = (f'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="{W}" xmlns:w14="{W14}">'
f'<w:body>{"".join(blocks)}<w:sectPr/></w:body></w:document>')
out = io.BytesIO()
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as archive:
archive.writestr("[Content_Types].xml", CONTENT_TYPES)
archive.writestr("_rels/.rels", RELATIONSHIPS)
archive.writestr("word/document.xml", document)
return out.getvalue(), len(document)
def body_paragraph(document, k):
return next(p for p in document.paragraphs if p.text.startswith(f"Paragraph {k} "))
CALLS = {
"Run.text": (lambda d, k: body_paragraph(d, k).runs[0], lambda d, run: setattr(run, "text", "changed ")),
"Paragraph.text": (body_paragraph, lambda d, p: setattr(p, "text", "changed")),
"Paragraph.add_run": (body_paragraph, lambda d, p: p.add_run(" more")),
"Table.add_row": (lambda d, k: d.tables[0], lambda d, t: t.add_row()),
"Document.add_footnote": (body_paragraph, lambda d, p: d.add_footnote(p, "note")),
"Document.remove_content": (lambda d, k: k + 1, lambda d, index: d.remove_content(index)),
# Two calls that are already local in every body.
"Document.insert_paragraph": (lambda d, k: k + 1, lambda d, index: d.insert_paragraph(index, "inserted")),
"Cell.text": (lambda d, k: d.tables[0].cell(k % 6, 1), lambda d, cell: setattr(cell, "text", "changed")),
}
def cost(count, saved, target, call):
document = rdocx.Document.from_bytes(package(count, saved)[0])
times = []
# Paragraphs 95, 75, 55 of 100 and 245, 225, 205 of 400, the last one first: an edit shifts what follows it.
for k in (count // 2 + 45, count // 2 + 25, count // 2 + 5):
subject = target(document, k)
started = time.perf_counter()
call(document, subject)
times.append(time.perf_counter() - started)
return 1000 * statistics.median(times)
print(f"document.xml of {LARGE} paragraphs: {package(LARGE, False)[1]} bytes as rdocx writes it, "
f"{package(LARGE, True)[1]} bytes as saved")
failed = False
for name, (target, call) in CALLS.items():
small, large = cost(SMALL, True, target, call), cost(LARGE, True, target, call)
written = cost(LARGE, False, target, call)
ok = large <= 1.5 * small + 1
failed |= not ok
print(f"{'PASS' if ok else 'FAIL'} {name}: as saved {small:.2f} ms at {SMALL} paragraphs, {large:.2f} ms at "
f"{LARGE} (x{large / small:.1f}); as rdocx writes it {written:.2f} ms at {LARGE}")
sys.exit(1 if failed else 0)Output on v0.17.0:
rdocx 0.17.0, Python 3.13.16, Linux x86_64
document.xml of 400 paragraphs: 55773 bytes as rdocx writes it, 106444 bytes as saved
FAIL Run.text: as saved 14.58 ms at 100 paragraphs, 54.75 ms at 400 (x3.8); as rdocx writes it 16.32 ms at 400
FAIL Paragraph.text: as saved 2.40 ms at 100 paragraphs, 8.79 ms at 400 (x3.7); as rdocx writes it 1.74 ms at 400
FAIL Paragraph.add_run: as saved 3.46 ms at 100 paragraphs, 12.61 ms at 400 (x3.6); as rdocx writes it 3.50 ms at 400
FAIL Table.add_row: as saved 17.45 ms at 100 paragraphs, 59.62 ms at 400 (x3.4); as rdocx writes it 14.91 ms at 400
FAIL Document.add_footnote: as saved 18.60 ms at 100 paragraphs, 63.85 ms at 400 (x3.4); as rdocx writes it 13.88 ms at 400
FAIL Document.remove_content: as saved 17.24 ms at 100 paragraphs, 67.28 ms at 400 (x3.9); as rdocx writes it 0.20 ms at 400
PASS Document.insert_paragraph: as saved 0.09 ms at 100 paragraphs, 0.24 ms at 400 (x2.6); as rdocx writes it 0.23 ms at 400
PASS Cell.text: as saved 1.77 ms at 100 paragraphs, 1.78 ms at 400 (x1.0); as rdocx writes it 1.42 ms at 400
exit=1
Suggested acceptance: every line prints PASS, and on the two public files the calls of the table cost what the local routes cost there today, a few milliseconds.
How we got here
- 0.16.0: a text edit wrote the model in place, and a handle was a position that nothing checked (rdocx and rpptx Python: first-draft script success, raw XML access, stable handles, no silent failures #316).
- 0.16.1: the checked owner inventory made handles safe. Every call then cost the document (Python: opening a document and every edit rescan all table cells, so filling a 240-cell table takes 134 s in v0.16.1 (1.9 s in v0.16.0) #378, Python: since v0.16.1 each paragraph or cell handle costs a time that grows with the document, so walking cell paragraphs takes minutes to hours (instant in v0.16.0) #398): about 19 s for one
Run.texton the 22-page file. - 0.16.2 to 0.17.0: Python: one structural edit costs a time that grows with the whole package (rpptx shape edits, rdocx replace_xml and remove_content), so building a deck takes minutes #389, rdocx Python: Paragraph.xml, insert_paragraph and remove_content cost a time in proportion to the body's XML size (follow-up of #389) #407, rdocx Python: the cost of an edit grows with styles.xml, the body and the cell's place in the table (filling a table is quadratic) #437 and rdocx Python: cell setters still grow with the body after #443, and open + try_replace_text costs twice the CLI #445 each named calls with a synthetic script, and each release made those calls local for the shape of the script. On real files the gain is large where a route applies (an insertion went from about 260 ms to 0.7 ms in 0.16.4,
Cell.textfrom 214 ms to 27 ms in 0.17.0) and absent elsewhere. - Our share: our scripts and our downstream timing test build their bodies with rdocx or python-docx, so they hold plain paragraphs only. They could not show this, and the gates pinned from them cannot either. That is why this issue names no call.
What we ask
- One decision on the mechanism instead of one more route per call: an unchanged block should cost nothing in a call, whatever it holds. rpptx works this way since rpptx: share unchanged parts between a deck and its edit candidate, rebuild only the touched owner inventory (#403, part 1) #413 and rpptx: commit package edits in memory, reparsing only the parts that changed (#403, part 2, stacked on #413) #416 (a deck and its candidate share the unchanged parts, only the changed part is read again), and on two public PowerPoint decks the same kinds of edits cost under 1.5 ms. In Word the body is one part, so the unit would be the body block.
- Edit cost judged on bodies as Word saves them, with the script above or public files, beside the pinned scripts.
#437 and #445 stay open for their own criteria. A comment below proposes how the work could be split.
How the table was measured
One venv per version (pip install rdocx==X, or python-docx), then python measure_public_file.py FILE or python measure_public_file.py FILE python-docx.
"""The cost of one edit in a public document, with the rdocx installed or with python-docx.
Usage: measure_public_file.py FILE [python-docx]
Each call is timed on three paragraphs with text in the middle of the body, in a document opened for that call.
Prints the median in milliseconds. A call the library does not have prints its error.
"""
import io
import re
import statistics
import sys
import time
import zipfile
from xml.etree import ElementTree
raw = open(sys.argv[1], "rb").read()
W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
children = list(ElementTree.fromstring(zipfile.ZipFile(io.BytesIO(raw)).read("word/document.xml")).find(W + "body"))
texted = [k for k, child in enumerate(children) if child.tag == W + "p"
and child.find(f"{W}pPr/{W}sectPr") is None and (child.findtext(f"{W}r/{W}t") or "").strip()]
slots = texted[len(texted) // 2:len(texted) // 2 + 3] # direct body indexes
ordinals = [sum(child.tag == W + "p" for child in children[:k]) for k in slots] # indexes in Document.paragraphs
if sys.argv[2:] == ["python-docx"]:
import docx
opened, save = (lambda: docx.Document(io.BytesIO(raw))), (lambda d: d.save(io.BytesIO()))
else:
import rdocx
opened, save = (lambda: rdocx.Document.from_bytes(raw)), (lambda d: d.to_bytes())
paragraph = lambda d, i: d.paragraphs[ordinals[i]]
changed = lambda p: (p, re.sub(r"(<w:t[^>]*>)[^<]", r"\1Z", p.xml, count=1))
CALLS = {
"Run.text": (lambda d, i: paragraph(d, i).runs[0], lambda d, run: setattr(run, "text", "changed text")),
"Paragraph.text": (paragraph, lambda d, p: setattr(p, "text", "changed paragraph")),
"Paragraph.add_run": (paragraph, lambda d, p: p.add_run(" more")),
"Paragraph.insert_paragraph_before": (paragraph, lambda d, p: p.insert_paragraph_before("inserted")),
"Document.add_paragraph": (lambda d, i: None, lambda d, _: d.add_paragraph("appended")),
"Cell.text": (lambda d, i: d.tables[0].cell(0, 0), lambda d, cell: setattr(cell, "text", "changed")),
"Table.add_row": (lambda d, i: d.tables[0], lambda d, table: table.add_row()),
"Paragraph.replace_xml": (lambda d, i: changed(paragraph(d, i)), lambda d, pair: pair[0].replace_xml(pair[1])),
"Document.remove_content": (lambda d, i: slots[-1 - i], lambda d, index: d.remove_content(index)),
"Document.add_footnote": (paragraph, lambda d, p: d.add_footnote(p, "note")),
"save": (lambda d, i: None, lambda d, _: save(d)),
}
started = time.perf_counter()
opened()
print(f"{'open':36s} {1000 * (time.perf_counter() - started):10.2f} ms")
for name, (target, call) in CALLS.items():
try:
document, times = opened(), []
for i in range(3):
subject = target(document, i)
started = time.perf_counter()
call(document, subject)
times.append(time.perf_counter() - started)
print(f"{name:36s} {1000 * statistics.median(times):10.2f} ms")
except Exception as error:
print(f"{name:36s} {type(error).__name__}: {str(error)[:60]}")
Activity
hadim commentedon Nov 18, 2026
@mantissaman do you want us to take this on, or would you rather do it in S96.1? Either is fine with us. If we do it, here is roughly how we would split it. Each pull request would be measured on the script above and on the two public files, and would compare its route with the whole path in debug builds, as #415 did.
Run.text,add_run,Paragraph.textParagraph.text,add_run, and the half ofTable.add_rowand of the notes that follows the reopenprepare_and_reopen_stagedand ofsaves_asread what an unchanged block already gaveremove_content,replace_xml, table structure, notes, picturesPull request 5 is the one where your invariants matter most, so it may be the one you prefer to write.
One question decides 4 and 5: does a fact of a block depend on the blocks before it? The F-X268 plan names "bookmark prefix facts" and "the tab source occurrence". If some facts do, tell us which ones, and the record of a block needs them in its key.
If you would rather do it yourselves, we would stop at 1 and measure your branches on the public files. #449 and #451 stay as they are in both cases.
hadim commentedon Nov 20, 2026
@mantissaman, a heads-up rather than a question.
First, thank you. You started rdocx and drove it to a full Word and PowerPoint stack in pure Rust, with a depth and a pace that are genuinely impressive. We have relied on it every day for months, and you integrated a very large number of our reports. Hats off.
Our use, agents editing documents saved by Word and Google Docs, needs a faster edit path and shorter release cycles than your sprint process is built for, and we would rather not keep loading your queue with our timelines. So we are starting a friendly fork from v0.17.0, under a different name to avoid any confusion with the rdocx crates, beginning with the plan above. We will share the link once it is public.
This is not a disagreement about the project. We will keep filing issues here, with reproduction scripts, whenever a bug we find also affects rdocx, and once the fork is public you are welcome to take anything from it under the same MIT/Apache-2.0 licence. #448 to #454 stay open for you to use or close as you prefer.