Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions Lib/email/header.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,18 +89,24 @@ def decode_header(header):
words = []
for line in header.splitlines():
parts = ecre.split(line)
i = 0
parts_len = len(parts)
first = True
while parts:
unencoded = parts.pop(0)
while i < parts_len:
unencoded = parts[i]
i += 1
if first:
unencoded = unencoded.lstrip()
first = False
if unencoded:
words.append((unencoded, None, None))
if parts:
charset = parts.pop(0).lower()
encoding = parts.pop(0).lower()
encoded = parts.pop(0)
if i < parts_len:
charset = parts[i].lower()
i += 1
encoding = parts[i].lower()
i += 1
encoded = parts[i]
i += 1
Comment on lines +104 to +109
Copy link
Member

Choose a reason for hiding this comment

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

This may get out of range. You need a check after each i += 1. Because of that I'm not really interested in a 2% speed-up. Usually, we are interested in 10% speed-up when it comes down to a microbenchmark. In addition, your benchmark includes the import time as it's not part of the setup.

Copy link
Contributor Author

@heikkitoivonen heikkitoivonen Jan 9, 2026

Choose a reason for hiding this comment

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

The original code has the same issue, 3 pop(0) calls in succession without checking if any elements remain. So my code retains the same behavior.

I'll create a proper benchmark.

Copy link
Member

Choose a reason for hiding this comment

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

Actually I was wrong. The split would always have 3 parts because of the regex.

words.append((encoded, encoding, charset))
# Now loop over words and remove words that consist of whitespace
# between two encoded strings.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Speed up :func:`email.header.decode_header` by 1.02x.
Loading