4 min read
Strip tags from HTML fragments with html.parser.HTMLParser vs regex. This lab reports docs/s on Linux localhost, plus script/entity behavior checks.
Related links:
Lab honesty (1 Oct 2026 IST): Python 3.13.5. Affiliates: 0. Differentiates from html-escape-vs-manual (lab 105) — that post escaped text; this one strips markup.
Verdict up front (small doc 324 bytes, n=5000): regex ~243373 docs/s; html.parser ~14389. Bigger doc (2600 B): regex ~36491 vs parser ~1866.
| Arm | Pattern |
|---|---|
| HTMLParser subclass | skip script/style; join data |
| regex strip | drop script/style blocks then tags |
| both on 8× doc | scale check |
Seven rounds, p50. Fragment includes attrs, comment, entities, nested tags.
Script: lab-evidence/127-html-parser-vs-regex/results/run_lab.py.
| Arm | docs/s |
|---|---|
| regex small | 243373 |
| html.parser small | 14389 |
| regex big | 36491 |
| html.parser big | 1866 |
Regex led throughput by a wide margin on both sizes. Correctness is the other axis.
alert not in text).& → &); regex left & / < in the stripped string.'\n\nAlert severity\nLatency was 12.5 ms & rising — see link.\n\nonetwo <three>\n''\n\nAlert severity\nLatency was 12.5 ms & rising — see link.\n\nonetwo <three>\n'Fast regex is not a full HTML stack — nested oddities, malformed tags, and CDATA will diverge.
On the small fragment, regex ran about 16.9× the parser docs/s (~243373 vs ~14389). That gap buys you speed, not a DOM. If on-call pastes alert HTML into a ticket field, prefer the parser when humans must read decoded & as &.
Pair strip choice with an explicit unit fixture for script leak and entity decode — speed alone will pick regex every time and hide the fidelity bug.
On the 8× document (2600 bytes), regex still led (~36491 docs/s) while the parser sat near ~1866. Absolute docs/s fell for both as expected; the fidelity gap (entities) did not close with size. Measure your own corpus before codifying a strip helper in a shared library.
> inside attributes.Evidence: summary.json, summary.txt.
One Linux box. Stdlib only. Not BeautifulSoup/lxml, not XSS filters.
Regex strip hit ~243373 docs/s vs parser ~14389 on the small doc — but the parser decoded entities. Pick regex for speed on simple trusted markup; pick html.parser when decode and tag structure matter.
Lab evidence
Lab 1 Oct 2026 IST. Python 3.13.5. small: regex 243373 docs/s; html.parser 14389. Parser decodes entities; regex left &. Affiliates: 0. Evidence: lab-evidence/127-html-parser-vs-regex/. script_leaked=False on both inputs.
Summary1 Oct 20263 min read
Hands-on gc.collect cost empty vs cyclic garbage lab: real collect latency plus reclaim counts, measured on Linux localhost today in this lab for SREs.
Hands-on1 Oct 20264 min read
Hands-on fractions.Fraction vs float for exact ratios: real ops/s and exactness checks, measured on Linux localhost today in this hands-on lab for SREs.
Summary1 Oct 20264 min read