perf: cut allocations 2x in DOM traversal for ~1.6x faster conversion#41
Merged
Conversation
Profiling Html2Text.convert on the 1.4MB huge-msoffice fixture showed
GC accounting for 41% of wall time, driven by 1.37M object allocations
per convert — mostly node.name.downcase being recomputed ~19 times per
node across iterate_over, prefix_whitespace, suffix_whitespace and
next_node_name, plus per-node Array/map/compact/join churn.
Changes, all behavior-preserving (output is byte-identical on every
spec fixture):
- iterate_over computes node.name.downcase once per node and reuses it
- children are appended into a single mutable string instead of
building an Array, mapping, compacting and joining per node
- suffix_whitespace calls next_node_name once instead of twice for
br/div nodes
- merged duplicate h1-h6/p case branches, removing the need for the
Lint/DuplicateBranch disables
- dropped no-op /im regex flags and simplified /\n\n\n*/ to /\n{3,}/
Method signatures and return types are unchanged so subclasses that
override these methods (supported since #30) are unaffected; new specs
pin those extension points, and were verified to pass against the old
implementation as well.
Benchmarks (Ruby 4.0.5, arm64 macOS):
huge-msoffice (1.4MB) x5: 0.852s -> 0.522s (1.63x)
full_email (15KB) x500: 0.340s -> 0.269s (1.26x)
allocations (1x 1.4MB): 1,367,401 -> 642,896 (2.1x fewer)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
6bc7c9a to
bbe99c8
Compare
moberegger
reviewed
Jul 8, 2026
There was a problem hiding this comment.
Pull request overview
This PR optimizes Html2Text’s DOM traversal to reduce per-node allocations during conversion, aiming to improve throughput and lower GC pressure on large HTML documents. It also adds targeted specs to pin key class methods and subclass extension points relied on by consumers.
Changes:
- Reduced allocations in
iterate_overby caching the downcased node name per node and building child output via a single mutable string instead of array/map/compact/join. - Minor whitespace/regex simplifications and reduced duplicate calls to
next_node_nameinsuffix_whitespace. - Added new specs for class methods (
fix_newlines,replace_entities) and subclass override/dispatch behavior.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| lib/html2text.rb | Refactors traversal and whitespace handling to reduce allocations and improve conversion performance. |
| spec/subclass_spec.rb | Adds specs asserting supported subclass override points and self.convert dispatch behavior. |
| spec/class_methods_spec.rb | Adds unit specs covering fix_newlines and replace_entities. |
| CHANGELOG.md | Documents the performance work and newly added specs in the Unreleased section. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Review suggestion from #41. Measured ~1.5x faster than Array#include? on a realistic mostly-miss tag mix, though the end-to-end effect is negligible (one lookup per element node). Set autoloads without a require since Ruby 3.2 and this gem requires 3.3+. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The changelog claimed subclass specs covered suffix_whitespace, but no spec exercised it. Add one so the claim is true. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
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.
Summary
Profiling
Html2Text.convert(stackprof, wall + object modes) against this repo's ownhuge-msoffice.htmlfixture (1.4MB) showed:String#downcaseand 375K (27%) fromNokogiri::XML::Node#node_name—node.name.downcasewas being recomputed ~19 times per node acrossiterate_over,prefix_whitespace,suffix_whitespaceandnext_node_nameArray→map→compact→joininiterate_over, which also re-copies each subtree's text at every tree levelChanges
All behavior-preserving — output is byte-identical on every fixture in
spec/examples/(verified by a side-by-side harness during development, and the full suite passes unchanged):iterate_overcomputesnode.name.downcaseonce per node and reuses it for all checkssuffix_whitespacecallsnext_node_nameonce instead of twice forbr/divh1-h6/pcase branches, removing theLint/DuplicateBranchdisables/imregex flags and simplified/\n\n\n*/to/\n{3,}/Method signatures and return types are deliberately unchanged, so subclasses that override
prefix_whitespace,suffix_whitespace,iterate_over,wrap_linkorimage_text(supported since #30) are unaffected.Benchmarks
Ruby 4.0.5, arm64 macOS, fixtures from
spec/examples/, with and without YJIT (50-iteration warmup so YJIT compiles the hot paths):YJIT narrows the large-document gap somewhat (it cheapens the redundant method calls) but can't eliminate object allocations — allocation counts are identical with and without YJIT, and GC pressure was the dominant cost, so the win holds up under YJIT. The allocation reduction also lowers GC pressure process-wide for apps converting many documents.
New tests
spec/subclass_spec.rb— pins the subclass extension points (prefix_whitespace,wrap_link,iterate_over,image_text, andself.convertdispatch), which were previously untested despite being an advertised featurespec/class_methods_spec.rb— unit specs forfix_newlinesandreplace_entitiesAll new tests were verified to pass against the old implementation as well (run in a clean master worktree), so they pin pre-existing behavior rather than new behavior. 64 examples, 0 failures; rubocop clean.
Not changed (noted for the record)
The
divhandling inprefix_whitespacecomparesnode.parent.text.strip == node.text.strip, which serializes both subtrees for every nested div — O(n²) in the worst case. Stress tests with quote-chains up to depth 800 stayed fast in absolute terms, so it's left alone here; fixing it would need a structural check with subtle output-semantics risk.🤖 Generated with Claude Code