Skip to content

Commit bbe99c8

Browse files
mscrivoClaude Fable 5
andcommitted
Reduce allocations in iterate_over for ~1.6x faster conversion
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>
1 parent 8b11493 commit bbe99c8

4 files changed

Lines changed: 122 additions & 35 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
88
### Changed
99
- Require Ruby 3.3+; CI now tests Ruby 3.3, 3.4 and 4.0 ([#42](https://github.com/soundasleep/html2text_ruby/pull/42))
1010
- Update development dependencies (rubocop 1.88, nokogiri 1.19 in the lockfile), removing the transitive `rexml` dependency ([#42](https://github.com/soundasleep/html2text_ruby/pull/42))
11+
- Reduce object allocations in `iterate_over` for ~1.6x faster conversion of large documents ([#41](https://github.com/soundasleep/html2text_ruby/pull/41))
12+
13+
### Added
14+
- Specs covering subclass overrides of `prefix_whitespace`, `suffix_whitespace`, `iterate_over`, `wrap_link` and `image_text`, plus unit specs for `fix_newlines` and `replace_entities` ([#41](https://github.com/soundasleep/html2text_ruby/pull/41))
1115

1216
## [0.4.0](https://github.com/soundasleep/html2text_ruby/compare/0.3.1...v0.4.0) - 2024-06-08
1317
### Added

‎lib/html2text.rb‎

Lines changed: 22 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ def convert
5050
end
5151

5252
DO_NOT_TOUCH_WHITESPACE = '<do-not-touch-whitespace>'
53+
IGNORED_TAGS = %w[style head title meta script].freeze
5354

5455
def remove_leading_and_trailing_whitespace(text)
5556
# ignore any <pre> blocks, which we don't want to interact with
@@ -74,60 +75,51 @@ def remove_leading_and_trailing_whitespace(text)
7475
private
7576

7677
def remove_unnecessary_empty_lines(text)
77-
text.gsub(/\n\n\n*/im, "\n\n")
78+
text.gsub(/\n{3,}/, "\n\n")
7879
end
7980

8081
def trimmed_whitespace(text)
8182
# Replace whitespace characters with a space (equivalent to \s)
8283
# and force any text encoding into UTF-8
8384
if text.valid_encoding?
84-
text.gsub(/[\t\n\f\r ]+/im, ' ')
85+
text.gsub(/[\t\n\f\r ]+/, ' ')
8586
else
8687
text.force_encoding('WINDOWS-1252')
8788
trimmed_whitespace(text.encode('UTF-16be', invalid: :replace, replace: '?').encode('UTF-8'))
8889
end
8990
end
9091

9192
def iterate_over(node)
92-
return "\n" if node.name.downcase == 'br' && next_node_is_text?(node)
93-
9493
return trimmed_whitespace(node.text) if node.text?
9594

96-
return '' if %w[style head title meta script].include?(node.name.downcase)
95+
name = node.name&.downcase
9796

98-
return "\n#{DO_NOT_TOUCH_WHITESPACE}#{node.text}#{DO_NOT_TOUCH_WHITESPACE}" if node.name.downcase == 'pre'
97+
return '' if name.nil? || IGNORED_TAGS.include?(name)
9998

100-
output = []
99+
return "\n" if name == 'br' && next_node_is_text?(node)
101100

102-
output << prefix_whitespace(node)
103-
output += node.children.map do |child|
104-
iterate_over(child) unless child.name.nil?
105-
end
106-
output << suffix_whitespace(node)
101+
return "\n#{DO_NOT_TOUCH_WHITESPACE}#{node.text}#{DO_NOT_TOUCH_WHITESPACE}" if name == 'pre'
107102

108-
output = output.compact.join || ''
103+
return image_text(node) if name == 'img'
109104

110-
unless node.name.nil?
111-
if node.name.downcase == 'a'
112-
output = wrap_link(node, output)
113-
elsif node.name.downcase == 'img'
114-
output = image_text(node)
115-
end
105+
output = +''
106+
output << (prefix_whitespace(node) || '')
107+
node.children.each do |child|
108+
output << iterate_over(child)
116109
end
110+
output << (suffix_whitespace(node) || '')
111+
112+
output = wrap_link(node, output) if name == 'a'
117113

118114
output
119115
end
120116

121-
# rubocop:disable Lint/DuplicateBranch
122117
def prefix_whitespace(node)
123118
case node.name.downcase
124119
when 'hr'
125120
"\n---------------------------------------------------------------\n"
126121

127-
when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul'
128-
"\n\n"
129-
130-
when 'p'
122+
when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'p'
131123
"\n\n"
132124

133125
when 'tr'
@@ -147,33 +139,28 @@ def prefix_whitespace(node)
147139
'- '
148140
end
149141
end
150-
# rubocop:enable Lint/DuplicateBranch
151142

152-
# rubocop:disable Lint/DuplicateBranch
153143
def suffix_whitespace(node)
154144
case node.name.downcase
155-
when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
156-
# add another line
157-
"\n\n"
158-
159-
when 'p'
145+
when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p'
160146
"\n\n"
161147

162148
when 'br'
163-
"\n" if next_node_name(node) != 'div' && !next_node_name(node).nil?
149+
next_name = next_node_name(node)
150+
"\n" if !next_name.nil? && next_name != 'div'
164151

165152
when 'li'
166153
"\n"
167154

168155
when 'div'
169156
if next_node_is_text?(node)
170157
"\n"
171-
elsif next_node_name(node) != 'div' && !next_node_name(node).nil?
172-
"\n"
158+
else
159+
next_name = next_node_name(node)
160+
"\n" if !next_name.nil? && next_name != 'div'
173161
end
174162
end
175163
end
176-
# rubocop:enable Lint/DuplicateBranch
177164

178165
# links are returned in [text](link) format
179166
def wrap_link(node, output)

‎spec/class_methods_spec.rb‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# frozen_string_literal: true
2+
3+
require 'spec_helper'
4+
5+
describe Html2Text do
6+
describe '.fix_newlines' do
7+
it 'converts \r\n to \n' do
8+
expect(Html2Text.fix_newlines("hello\r\nworld")).to eq("hello\nworld")
9+
end
10+
11+
it 'converts bare \r to \n' do
12+
expect(Html2Text.fix_newlines("hello\rworld")).to eq("hello\nworld")
13+
end
14+
end
15+
16+
describe '.replace_entities' do
17+
it 'replaces &nbsp; entities with spaces' do
18+
expect(Html2Text.replace_entities('hello&nbsp;world')).to eq('hello world')
19+
end
20+
21+
it 'replaces non-breaking space characters with spaces' do
22+
expect(Html2Text.replace_entities("hello\u00a0world")).to eq('hello world')
23+
end
24+
25+
it 'removes zero-width non-joiners' do
26+
expect(Html2Text.replace_entities('hello&zwnj;world')).to eq('helloworld')
27+
end
28+
end
29+
end

‎spec/subclass_spec.rb‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# frozen_string_literal: true
2+
3+
require 'spec_helper'
4+
5+
# Subclassing Html2Text to override the default behaviour is supported
6+
# (see #30); these specs pin the extension points that subclasses rely on.
7+
class CustomListPrefix < Html2Text
8+
private
9+
10+
def prefix_whitespace(node)
11+
return '* ' if node.name.downcase == 'li'
12+
13+
super
14+
end
15+
end
16+
17+
class CustomLinkFormat < Html2Text
18+
private
19+
20+
def wrap_link(node, output)
21+
"#{output.strip} <#{node.attribute('href')}>"
22+
end
23+
end
24+
25+
class SkipsBlockquotes < Html2Text
26+
private
27+
28+
def iterate_over(node)
29+
return '' if !node.text? && node.name.downcase == 'blockquote'
30+
31+
super
32+
end
33+
end
34+
35+
class CustomImageText < Html2Text
36+
private
37+
38+
def image_text(node)
39+
"(image: #{node.attribute('src')})"
40+
end
41+
end
42+
43+
describe 'subclassing Html2Text' do
44+
it 'can override prefix_whitespace' do
45+
text = CustomListPrefix.convert('<ul><li>one</li><li>two</li></ul>')
46+
expect(text).to eq("* one\n* two")
47+
end
48+
49+
it 'can override wrap_link' do
50+
text = CustomLinkFormat.convert('<a href="http://example.com">hello</a>')
51+
expect(text).to eq('hello <http://example.com>')
52+
end
53+
54+
it 'can override iterate_over' do
55+
text = SkipsBlockquotes.convert('<p>before</p><blockquote>quoted</blockquote><p>after</p>')
56+
expect(text).to eq("before\n\nafter")
57+
end
58+
59+
it 'can override image_text' do
60+
text = CustomImageText.convert('<img src="pic.png" alt="a picture">')
61+
expect(text).to eq('(image: pic.png)')
62+
end
63+
64+
it 'uses the subclass from self.convert' do
65+
expect(CustomListPrefix.convert('plain text')).to eq('plain text')
66+
end
67+
end

0 commit comments

Comments
 (0)