Skip to content

perf: 2-4x faster rendering, half the memory on large tables - #56

Open
serpentblade wants to merge 13 commits into
dskripchenko:mainfrom
serpentblade:perf/table-layout
Open

serpentblade wants to merge 13 commits into
dskripchenko:mainfrom
serpentblade:perf/table-layout

Conversation

@serpentblade

@serpentblade serpentblade commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Thirteen commits that make rendering 2–4× faster, and text drawn with an embedded font another 18–33% faster on top. Large tables use about half the memory, and long text with an embedded font uses a fraction of it. Each commit stands on its own and can be reviewed separately.

composer bench, main → this branch, same machine (PHP 8.4, median of 5 isolated runs):

Scenario main this branch mpdf tcpdf dompdf
100-page invoice 2129 ms / 52 MB 515 ms / 28 MB 4693 ms 2600 ms 23754 ms
100-page invoice with a "Page X of Y" footer 2123 ms 528 ms 4694 ms 2618 ms 23941 ms
HTML article 54 ms 19 ms 94 ms 92 ms 87 ms
SVG dashboards (new scenario) 774 ms 378 ms 398 ms 1439 ms 528 ms
Image grid 8.3 ms 8.0 ms 43 ms 49 ms 49 ms
Hello world 5.9 ms 5.9 ms 33 ms 48 ms 14 ms

These scenarios use the base-14 fonts, so the four font commits don't change them (re-measured: within ±1%).

With an embedded font (Liberation Sans), main (1.27.0) → the first nine commits → this branch, median of 5 alternating processes:

Scenario main layout commits this branch
25 chapters of prose, 29 pages 461 ms / 53.0 MB 124 ms / 52.6 MB 80 ms / 1.9 MB
100-page invoice, 25 rows a page 528 ms / 28.3 MB 136 ms / 20.1 MB 111 ms / 16.5 MB
70 pages laid out by the caller, drawn line by line through Page::showEmbeddedText 315 ms / 73.2 MB 314 ms / 73.2 MB 234 ms / 7.0 MB

What each commit does:

  • Stop re-measuring top-aligned cells, cache font lookup. A top-aligned cell's content was measured again only to be drawn at the same place.
  • Share one default style instead of a copy per element. Every run, paragraph and cell built its own copy of the same default style.
  • Render once unless the document shows the page total. Every render laid the document out twice, only to count pages for NUMPAGES. Documents without a page total now take one pass.
  • Cache text widths for the length of a render. Each word was measured three times, and tables repeat the same words row after row. The 100-page invoice made 126,300 width calls for 4,100 distinct strings.
  • Trim per-word overhead in layout and content streams. Fewer style copies, string escaping in one strtr, and Base-14 widths summed in one call.
  • Bench: an SVG dashboards scenario. Ten different metrics dashboards of about 1,200 shapes each. The files differ so that a library caching images by file name still draws every page.
  • SVG: compose nested transforms into one matrix. A point is mapped once instead of once per nested group.
  • SVG: take a shape's ancestors from the walk. Inherited properties come from the tree walk instead of an XPath query per shape.
  • Redraw page totals in place instead of a second pass. When the total appears only in headers and footers, they are drawn again with the real count and swapped into each page. A full second pass still runs whenever that could change the result: a total in the body, a header or footer that changes height, or a redraw that would add an annotation or resource.
  • Font: build glyph and codepoint lists only for ligatures. shapedGlyphs() built two lists with closures on every call that only the ligature path reads. Also adds a test that checks encodeText() and encodeTextTjArray() against a plain reference, output and ToUnicode bookkeeping alike.
  • Font: decode text below U+0590 without the shaping scans. One max() replaces three scans for Arabic, Indic and Hebrew; glyphs come from the cmap in one call. ASCII and valid UTF-8 decode in C; malformed input keeps the existing loop.
  • Font: hoist font lookups out of the text-encoding loop. The kerning table and em size are read once per string, and each glyph's hex code is formatted once per font.
  • Font: encode drawn text from glyph-id lists. Without ligatures, drawn text goes from codepoints to glyph ids without per-glyph entries and stays out of the decode cache, which had been holding most of a long document's memory. Kerning comes from one KerningTable::lookupRun() call per string.

Output is byte-identical to main with two exceptions:

The page-total redraw was also checked against the two-pass output on 30 header and footer layouts: centred, right-aligned, first-page, offset sections, tagged, watermark, footnotes, tables, coloured text and an embedded font. The font commits were also checked across Latin, Cyrillic, Hebrew, Arabic, CJK, a CFF font with ligatures, emoji and malformed UTF-8, with and without letter spacing.

Rebased onto 1.27.0. The SVG transform commit now wraps each shape in withDash(), so dashed strokes keep working inside transformed groups; SvgStrokeDashTest passes.

The full test suite and phpstan pass on PHP 8.2 and 8.4. This branch merges cleanly with #55. It conflicts with #54 in PdfFont::decodeUtf8(), because the font commits move the cache insert there: keep this branch's decodeUtf8() and put #54's eviction block in place of the old one. With that, the suite and phpstan pass on the three combined.

I haven't regenerated docs/en/BENCHMARKS.md or the README tables, so the published numbers come from your machine. composer bench -- --docs refreshes them and adds the SVG scenario.

🤖 Generated with Claude Code

serpentblade and others added 13 commits November 11, 2026 17:39
Every table cell's content was measured twice: once for the row height
and again in renderCellContent, where the height only matters for
center or bottom alignment. Top-aligned cells, the default, now skip
the second measure.

standardFontFor re-parsed the CSS font-family list for every word it
measured. The base-14 face is now cached per family/bold/italic, and
the parsed family list is cached too (capped at 256 entries for
long-running workers).

The 100-page invoice bench drops from ~920ms to ~685ms with
byte-identical output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Run, Paragraph, Cell and Field each created their own all-defaults
RunStyle, ParagraphStyle or CellStyle, as did the cell and paragraph
builders: four style objects per plain table cell. The style classes
are immutable, so each now has a shared default() instance that
elements fall back to when no style is given. The constructors take
?XStyle $style = null; existing callers are unaffected.

A plain cell drops from ~1.9KB to ~800 bytes. The 100-page invoice
bench peaks at 25MB instead of 47MB, with byte-identical output.
effectiveCellStyle no longer allocates a CellStyle per cell to compare
against.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Engine::render always laid the document out twice: the first pass only
counted pages so NUMPAGES fields could show the total. Most documents
have no NUMPAGES, so half of every render was thrown away.

The first pass now records whether it resolved a NUMPAGES field, and
is returned as the result when it didn't. Outline entries, previously
skipped in the first pass to save work, are registered on every pass.

Render time halves for documents without a page total, with
byte-identical output: the 100-page invoice bench drops from ~630ms to
~320ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
measureWidth ran for every word three times — for the block's height,
for line breaking and when drawing — and tables repeat the same words
row after row: a 100-page invoice made 126,300 calls for 4,100
distinct inputs. Widths are now cached by size, weight, slant, family
and text for one render. The cache is cleared when the render ends and
starts over past 20,000 entries.

Render time drops 17-35% (the invoice ~315ms → ~265ms, with an
embedded font ~440ms → ~325ms) with no change in peak memory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Small costs paid for every word, each now cheaper with byte-identical
output:

- RunStyle::inheritFrom returns the other side when one side is all
  defaults, instead of building a copy; heading styles are built once
  per level.
- ContentStream::escapeString returns text with nothing to escape as
  is, and escapes the rest in one strtr instead of byte by byte.
- Base-14 widths are summed from the font's table in one call instead
  of one call per byte.
- spanWidth skips array_slice/array_sum for single-column cells,
  splitWords drops its filter closure, and the footnote walks skip
  text runs.

Render time drops 8-17% (the invoice ~265ms → ~235ms, real prose
~23ms → ~19ms) with no change in memory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ten pages, each a different metrics dashboard: a 4 x 3 grid of line,
bar, scatter and area charts with gridlines and labels, about 1,200
shapes a page. The files differ so that a library caching images by
name still draws every page. They are written before the clock starts,
through a bench_prepare_<scenario>() hook in one.php, and read inside
the timed run by every library. FPDF has no SVG and is skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Under a <g transform>, every coordinate went through a closure per
level of nesting, down to the page mapping, and px and py each worked
the same affine out again. The walk now multiplies each transform into
the page mapping on the way down, so a point costs one closure call
however deep it sits. The two walkers that each held the nine-way
element match share drawTransformed().

The SVG dashboards scenario drops from ~432 ms to ~394 ms (-9%).
Coordinates are rounded the same way but reached in a different order,
so about 1 line in 150 of the dense benchmark changes in its fourth
decimal; rendered at 720 dpi, 14-28 of ~50 million pixels a page
differ, by at most 8% in one channel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
inheritedProperty() looked a shape's ancestors up with an
ancestor-or-self XPath query, once per shape. The walk already knows
them: it now keeps the groups it is inside and hands each shape its
chain before drawing it. Any other element still goes through XPath.

The SVG dashboards scenario drops from ~394 ms to ~384 ms (-2.5%),
byte-identical output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A NUMPAGES field anywhere sent the whole document through layout twice,
only to learn the page count. "Page X of Y" in a footer is the usual
case, and there the body comes out the same on both passes; only the
footers change.

Pass 1 now notes where each header and footer showing the total was
drawn. Once the count is known they are drawn again with it and put in
place of what pass 1 drew. Pass 2 still runs whenever that could give a
different result:

- the total appears in the body or in a fixed block;
- a header or footer takes a different height with the real total than
  with the stand-in, so the body would move;
- the redraw adds anything to the page or document (a link annotation,
  a resource, an outline entry) or leaves the content stream in another
  state than the commands after it were written against.

Output is byte-identical to the two-pass render across the test suite
and 30 header/footer cases (centred, right-aligned, first-page, offset
sections, tagged, watermark, footnotes, tables, coloured, embedded
font). A 200-page invoice with a "Page X of Y" footer drops from
~1000ms to ~540ms, the same as without the footer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
shapedGlyphs() built a list of glyph ids and a list of codepoints with
two array_map closures on every call, though only the ligature path
reads them. Without a ligature table, which is common, both were thrown
away. They are now built after the check, with array_column.

Also adds PdfFontTextEncodingTest: encodeText() and encodeTextTjArray()
against a plain reference (shapedGlyphs, kerningPdfUnits per pair,
sprintf per glyph), checking both the output and what the font records
for its ToUnicode map, in order, after every string. It covers kerning,
CFF, ligatures on and off, Arabic, Hebrew, a glyph shared by two
codepoints, emoji and malformed UTF-8, and pins the next commits.

Text drawing with an embedded font: 25 pages of prose -4%, 100-page
invoice -2%. Output is byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
decodeUtf8() scanned every string three times for Arabic, Indic and
Hebrew, then looked up each codepoint's glyph with its own method call.
Every script that needs shaping or reordering starts at U+0590, so one
max() over the codepoints now decides: below it, the glyphs come from
the cmap in a single TtfFile::glyphIdsForChars() call; otherwise the
shaping pipeline runs as before, moved unchanged into shapeAndMap().

utf8ToCps() decodes ASCII with unpack() and valid UTF-8 through
mb_convert_encoding() to UTF-32. Malformed input keeps the existing
byte loop, so it decodes exactly as before.

Text drawing with an embedded font: 25 pages of prose -4%, 100-page
invoice -3%. Output is byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
encodeTextTjArray() called kerningPdfUnits() for every glyph pair, and
that fetched the kerning table and em size each time; each glyph's hex
code came from its own sprintf(). The table and em size are now read
once per string, and each glyph's hex code is formatted once per font
and kept. encodeText() shares the hex codes.

Text drawing with an embedded font: 25 pages of prose -8%, 100-page
invoice -5%. Output is byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
encodeTextTjArray() went through shapedGlyphs(), which builds an entry
per glyph and, through decodeUtf8(), caches whole lines that rarely come
back: at ~400 bytes per character, the cache held most of a long
document's memory.

Without ligatures, glyphs map one to one to codepoints. Drawn text now
goes from codepoints to a plain list of glyph ids, and text below U+0590
skips the decode cache. Shaped scripts and fonts with ligatures still go
through decodeUtf8() and shapedGlyphs(). Kerning for the whole string
comes from one KerningTable::lookupRun() call, and usedGlyphs is written
once per distinct glyph of the string, keeping the order and the
last-codepoint-wins rule of writing glyph by glyph.

Text drawing with an embedded font: 25 pages of prose -17%, peak memory
52.6 MB -> 1.9 MB; 100-page invoice -9%, 20.1 MB -> 16.5 MB. Output is
byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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