Skip to content

Share standard font metrics across documents - #1820

Open
gouz wants to merge 1 commit into
foliojs:masterfrom
gouz:perf/share-standard-font-metrics
Open

gouz wants to merge 1 commit into
foliojs:masterfrom
gouz:perf/share-standard-font-metrics

Conversation

@gouz

@gouz gouz commented Oct 15, 2026

Copy link
Copy Markdown

What kind of change does this PR introduce?

Performance fix. StandardFont builds a new AFMFont for every document, so each document that uses e.g. Helvetica rebuilds its glyph width and kerning tables from the same font data. AFMFont only reads that data after construction (nothing in lib/ writes to it), so one instance per font data is now kept in a WeakMap and shared. Keying on the data object means registerStdFonts() with replacement data still gets a fresh AFMFont.

Measured on Node 26, Apple Silicon, 2 000 documents with one heading in Helvetica-Bold and a paragraph in Helvetica (after 200 warm-up documents), 3 runs each:

ms per document
before 0.547 / 0.563 / 0.553
after 0.228 / 0.226 / 0.228

In a react-pdf HTML → PDF pipeline, profiling showed AFMFont construction at ~7% of CPU, and the change cut total render time by ~10%.

Checklist:

  • Unit Tests (standard font metrics are shared across documents fails without the change; full yarn test passes, 551 tests)
  • Documentation N/A
  • Update CHANGELOG.md
  • Ready to be merged

🤖 Generated with Claude Code

StandardFont built a new AFMFont for every document, rebuilding the glyph
width and kerning tables from the same font data each time. AFMFont only
reads that data, so keep one per font data in a WeakMap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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