Skip to content

Convert many sibling divs in linear time - #45

Merged
mscrivo merged 1 commit into
soundasleep:masterfrom
fschwahn:linear-div-whitespace-minimal
Nov 24, 2026
Merged

mscrivo merged 1 commit into
soundasleep:masterfrom
fschwahn:linear-div-whitespace-minimal

Conversation

@fschwahn

Copy link
Copy Markdown
Contributor

A nested div gets no leading line break if it has all of its parent's text, which was checked by comparing the parent's text with the div's. Computing the parent's text again for every child div made converting documents with many sibling divs quadratic: 625 KB of sibling divs took 13 seconds.

The stripped text lengths are now compared first, with the parent's length computed once. If a sibling has text, the parent's text is longer than the div's, so the texts are only compared for at most one child per parent.

As this library commonly runs on untrusted user input (ie. incoming emails), I think it's worth fixing this edge case. According to my measurements this allocates less objects than before despite the cache, because we exit early if lengths are different.

A nested div gets no leading line break if it has all of its parent's
text, which was checked by comparing the parent's text with the div's.
Computing the parent's text again for every child div made converting
documents with many sibling divs quadratic: 625 KB of sibling divs took
13 seconds.

The stripped text lengths are now compared first, with the parent's
length computed once. If a sibling has text, the parent's text is
longer than the div's, so the texts are only compared for at most one
child per parent.
Comment thread lib/html2text.rb
end

def stripped_text_length(node)
@stripped_text_lengths ||= {}.compare_by_identity

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably should reset this at the start of convert calls?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually on second thought, I don't think we need to

@mscrivo

mscrivo commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

thanks for your contribution @fschwahn!

@mscrivo
mscrivo merged commit f03bb30 into soundasleep:master Nov 24, 2026
6 checks passed
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.

2 participants