Repository navigation
perf: 2-4x faster rendering, half the memory on large tables - #56
Open
serpentblade wants to merge 13 commits into
Open
serpentblade wants to merge 13 commits into
serpentblade wants to merge 13 commits into
Conversation
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>
serpentblade
force-pushed
the
perf/table-layout
branch
from
November 12, 2026 02:41
783469e to
9144158
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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):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:
Page::showEmbeddedTextWhat each commit does:
NUMPAGES. Documents without a page total now take one pass.strtr, and Base-14 widths summed in one call.shapedGlyphs()built two lists with closures on every call that only the ligature path reads. Also adds a test that checksencodeText()andencodeTextTjArray()against a plain reference, output and ToUnicode bookkeeping alike.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.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;SvgStrokeDashTestpasses.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'sdecodeUtf8()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.mdor the README tables, so the published numbers come from your machine.composer bench -- --docsrefreshes them and adds the SVG scenario.🤖 Generated with Claude Code