Skip to content

email.header: folding a long header takes quadratic time #161284

Open

Description

@thejesh23

Bug report

Bug description:

email.header.Header.encode() is quadratic in the number of words on an unfolded line: _Accumulator.__len__() sums all its parts on every call, and _ValueFormatter._append_chunk() calls it after every word.

cpython/Lib/email/header.py

Lines 564 to 566 in 7e3290d

def __len__(self):
return sum((len(fws)+len(part) for fws, part in self),
self._initial_size)

Message.as_string() and mailbox write headers unfolded (maxheaderlen=0) with the default compat32 policy, so one long header is enough. A message with a 160 KB Subject: takes about 5 s in mailbox.mbox.add().

import email, time

msg = email.message_from_string('Subject: ' + 'word ' * 8000 + '\n\nbody\n')
start = time.perf_counter()
msg.as_string()
print(f'{time.perf_counter() - start:.3f} s')  # 0.806 s on main, 0.004 s with the fix

Same kind of problem as gh-136063, but in the compat32 email.header code.

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    type-bug
    stdlib
    on Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtopic-emailtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions