Skip to content

perf: streamline HTML serializer and cache inline pattern metadata per run - #1730

Open
alexander-src wants to merge 3 commits into
Python-Markdown:masterfrom
alexander-src:perf/serialize-html-and-inline-loop
Open

alexander-src wants to merge 3 commits into
Python-Markdown:masterfrom
alexander-src:perf/serialize-html-and-inline-loop

Conversation

@alexander-src

Copy link
Copy Markdown

Description

Profiling markdown.Markdown.convert on multi-section documents (tables, fenced code, TOC, inline formatting) pointed to two avoidable hot-loop costs:

  • markdown/serializers.py (_serialize_html): used a deque as a LIFO stack (popleft/appendleft/extendleft), maintained an unused count variable, called tag.lower() three times per element, constructed ["script", "style"] on each element, called el.items() + sorted() even when an element had no attributes, and pushed closing tags and tails onto the stack for childless leaf elements. Switching to a plain list stack, hoisting tag.lower() and _RAW_TEXT_TAGS, fast-pathing empty/single attribute dicts, and emitting leaf elements directly removes those allocations and extra stack passes.
  • markdown/treeprocessors.py (InlineProcessor): popped from the front of a list (stack.pop(0)) instead of a deque (popleft()), and re-ran Registry.__getitem__, isinstance(pattern, InlineProcessor), pattern.getCompiledRegExp(), and exclude.lower() inside __applyPattern on every text node. Snapshotting the pattern tuple once at the start of run() (and clearing it alongside parent_map / stashed_nodes on exit) avoids repeated lookups while preserving the .finditer() call path for custom patterns.

Benchmark on a 30x repeated mixed document (tables, fenced_code, toc extensions, 8 convert() runs, 20 interleaved A/B pairs with exact stdout SHA-256 verification via oa):

Metric master (27c01419) This PR Result
Median wall time 352.43 ms 307.57 ms 1.13x
p95 / MAD 393.60 / 14.21 ms 388.80 / 10.51 ms 95% CI [1.09x, 1.18x]
Peak RSS 30,512 KiB 28,848 KiB -5.5%
Output SHA-256 d2f546dea9d57569 identical Mann-Whitney U p = 0.0000

Verification: python -m unittest discover tests ran 1,230 tests (OK, 111 skipped).

AI Assistance Disclosure

  • No AI tools were used in preparing this PR.
  • AI tools were used and I have disclosed which ones, and have fully reviewed and verified their output.

AI tools were use to assist with the following (Antigravity coding assistant):

  • Code
  • Code Comments
  • Documentation
  • Changelog Entry
  • Commit Message
  • The Description Above
  • Other: ______________

Checklist

@waylan

waylan commented Nov 26, 2026

Copy link
Copy Markdown
Member

@facelessuser you recently added the use of deque to markdown/serializers.py in #1644. Any thoughts on this?

@waylan waylan added the needs-review Needs to be reviewed and/or approved. label Nov 26, 2026
@facelessuser

Copy link
Copy Markdown
Collaborator

@waylan, to be honest, the removal of deque matters little; keeping the deque is a matter of style in this specific case, not a bug. In short, it is perfectly appropriate to keep it, but it hurts nothing to use a plain list in the serializer either. With that said, the serializer rewrite is safe but saves little. The serializer is only about 3% of total conversion time. The rewrite trims about 17% of that, and the gain comes from writing childless elements directly and calling tag.lower() once. The deque swap contributes nothing.

The usage of deque in the treeprocessor is where we actually get some real gains. Generally, the treeprocessor changes are the part that is really worth having. Caching pattern metadata per run and replacing stack.pop(0) with deque.popleft() both help.

@alexander-src

Copy link
Copy Markdown
Author

Thanks @facelessuser, that breakdown makes a lot of sense. I reverted the markdown/serializers.py changes in b80fac6 so #1644 stays untouched and the PR stays focused on InlineProcessor in markdown/treeprocessors.py (pattern metadata snapshot per run() and deque.popleft()). Re-ran the suite (1,230 tests pass) and checked master vs the narrowed diff (184.2 -> 167.4 ms, 1.10x, -2.6% peak RSS, identical output SHA-256).

@facelessuser

Copy link
Copy Markdown
Collaborator

I didn't say you had to revert the serializer change, just noting that it contributed little to the overall time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-review Needs to be reviewed and/or approved.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants