Skip to content

gh-161284: Fix quadratic time in email.header when folding long headers - #161285

Open
thejesh23 wants to merge 5 commits into
python:mainfrom
thejesh23:email-header-accumulator
Open

thejesh23 wants to merge 5 commits into
python:mainfrom
thejesh23:email-header-accumulator

Conversation

@thejesh23

@thejesh23 thejesh23 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Keep a running total in email.header._Accumulator, updated in push(), pop(), pop_from() and reset(), instead of summing all parts on every len() call, which made Header.encode() quadratic in the number of words on a line.

Tested with new tests and a comparison against the old code on 60,000 random Header.encode() calls and 15,000 random messages through as_string() and as_bytes(). An 8,000-word header in as_string(): 0.8 s → 4 ms.

_Accumulator.__len__() summed the lengths of all the parts of the
current line on every call, and it is called after every appended
word, so folding a header whose line grows long took O(N**2) time.
This is the case for Message.as_string(), which does not fold headers
by default.  Keep the total length up to date instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant