Skip to content

gh-161977: Fix quadratic time in textwrap when breaking a long word - #161978

Open
thejesh23 wants to merge 10 commits into
python:mainfrom
thejesh23:textwrap-long-word
Open

thejesh23 wants to merge 10 commits into
python:mainfrom
thejesh23:textwrap-long-word

Conversation

@thejesh23

@thejesh23 thejesh23 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

textwrap.wrap() took quadratic time on a long word: each line broke off one piece and copied the rest of the word.

_wrap_chunks() now splits a long word into line-width pieces in one pass for the lines after the first, which all have the same width. It stops before the first whitespace or hyphen, which keep the old path, and at the max_lines limit. The output is unchanged.

input main this PR
base64 of 1 MiB, wrap(s, 76) 752 ms 72 ms
'x' * 1_400_000, wrap(s, 70) 744 ms 67 ms
'x' * 1_400_001, wrap(s, 70, max_lines=20_000) 870 ms 70 ms

(macOS, LTO+PGO build.)

Testing: new tests in test_textwrap, identical output to main on ~58,000 random inputs, and the test suites of the stdlib modules that use textwrap pass.

AI disclosure: prepared with the help of Claude Code; I reviewed the change and the test results.

TextWrapper._handle_long_word() broke off one line's worth of a long
word at a time and stored the rest back, copying the rest of the word
for every line.  Break the rest of the word into the pieces of all the
following lines in one pass instead.  They all have the same width, so
the result is the same.
Comment thread Lib/textwrap.py Resolved
Comment thread Lib/textwrap.py Resolved
@thejesh23

Copy link
Copy Markdown
Contributor Author

@maurycy thanks for the review I'm not sure why you have deleted your posted comment actually its a right catch , NEWS entry: use :mod: instead of naming functions.

@maurycy

maurycy commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

@thejesh23 I'm sorry, I've removed the one about NEWS accidentially, thank you for addressing it in 43c0f59.

That said:

  • Did you use PGO+LTO build to benchmark?
  • I'd move to the _wrap_chunks(). I'm not sure if the current complexity is worth it, especially given that 10-100k+ words (where this change shines) aren't really that frequent.
  • Could you not use AI to write text? Generally: https://devguide.python.org/getting-started/ai-tools/ but it's just hard to read

Thank you! 💚

@thejesh23

thejesh23 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor Author

@maurycy no worries .

  • Did you use PGO+LTO build to benchmark?

Actually used normal optimised build (./configure with -O3), without --enable-optimizations or --with-lto

  • I'd move to the _wrap_chunks(). I'm not sure if the current complexity is worth it, especially given that 10-100k+ words (where this change shines) aren't really that frequent.

Agree to move the splitting into _wrap_chunks().
Wrapping base64 data, a common idiom for PEM keys and MIME bodies, is one long word with no spaces or hyphens. I measured wrap(b64, 76) just now.

Still getting used to the used to all of repo rules . Irrespective of repo rules for responding/acting on comments I don't use AI ::)

Comment thread Lib/textwrap.py Resolved
@bedevere-app bedevere-app Bot added the type-feature A feature request or enhancement label Nov 16, 2026
@thejesh23

Copy link
Copy Markdown
Contributor Author

@serhiy-storchaka could you take a look when you have time? You worked on the long-word handling in gh-139065.

@thejesh23
thejesh23 requested a review from maurycy November 20, 2026 10:42

@sirosen sirosen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I did some testing to try to break this patch or make it produce different results from main, and the implementation held up. I don't see any flaws in it. 👍

I have some questions aimed at making the meaning clearer -- it's a pretty large amount of logic in a single condition.

Comment thread Lib/textwrap.py Outdated
if (lines and self.max_lines is None and self.break_long_words and
0 < width < len(word) and
not (self.break_on_hyphens and '-' in word) and
word.split(None, 1) == [word]):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

When would word.split(None, 1) not be equivalent to [word]? (Keeping in mind that the text wrapper already split out chunks based on a regex for whitespace chars.)

I think this might only hold in the case where word is entirely whitespace, in which case the condition is spelled elsewhere in this function using strip(). Is that right? The meaning here is not totally clear to me.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It also covers non-ASCII whitespace inside a word, since the chunk regex only splits on ASCII whitespace: without it, wrap('x aa' + '\xa0' * 6 + ' z', 4) gives ['x aa', '\xa0\xa0 z'] instead of ['x aa', ' z']. It was also slow, because it re-ran on every line. 80c8c53 replaces it with one regex search that stops at the first whitespace or hyphen. Tests added.

Comment thread Lib/textwrap.py Outdated
# long word for all of them at once. Breaking off one line at a
# time would copy the rest of the word each time.
word = chunks[-1]
if (lines and self.max_lines is None and self.break_long_words and

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm aware @maurycy requested the addition of max_lines is None as a check, but is that the right check? Would len(lines) + 1 < self.max_lines and width * (self.max_lines - len(lines)) > len(word) also be satisfactory?

(Possibly that needs an extra line of space as a safety margin, to ensure there's room to place a potential placeholder value.)

@maurycy maurycy Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm sorry for the radio silence in the PR. I'm travelling, and there's lots of subtlety.

I did not run any analysis before proposing self.max_lines is None, just noted redundant work. I think your variant is better, although I'd consider >=:

if (
    lines
    and 0 < width < len(word)
    and self.break_long_words
    and (
        self.max_lines is None
        or width * (self.max_lines - len(lines)) >= len(word)
    )
    and not (self.break_on_hyphens and '-' in word)
    and word.split(None, 1) == [word]
):

What do you think?

GPT-6.2-Astra xhigh assited, macOS LTO+PGO:

wall time (ms)
Input width max_lines main max_lines is None > >=
1,000,000 x, one line 2 1 32.16 31.99 32.03 31.98
1,000,000 x, two lines 2 2 32.45 32.21 32.26 32.23
1,000,000 x, three lines 70 3 32.40 32.28 32.30 32.26
1,400,000 x, unlimited 70 None 233.26 49.94 49.90 49.88
1,399,999 x, one character to spare 70 20,000 241.52 231.61 50.76 50.56
1,400,000 x, exact fit 70 20,000 241.69 232.72 230.39 50.95
1,400,001 x, one character over 70 20,000 242.72 226.19 227.03 227.24
Base64 of 1 MiB 76 20,000 224.02 215.19 52.81 52.83
262,144 x 70 4,000 17.76 17.46 9.59 9.54
262,144 characters, trailing NBSP + y 70 4,000 22.41 23.18 231.93 231.59
262,150 characters, trailing NBSP + y, exact fit 70 3,745 22.42 22.43 22.64 226.87
100,000 x, exact fit 2 50,000 75.85 77.26 78.83 15.65
1,400,000 x followed by next 70 20,000 234.69 225.69 226.43 50.68
200 Wikipedia articles 70 3 34.95 35.28 35.35 35.46
200 Wikipedia articles 70 4,000 43.19 43.30 43.90 43.91
`tracemalloc` (MB), all 15 inputs
Input width max_lines main max_lines is None > >=
1,000,000 x, one line 2 1 2.00 2.00 2.00 2.00
1,000,000 x, two lines 2 2 2.00 2.00 2.00 2.00
1,000,000 x, three lines 70 3 2.00 2.00 2.00 2.00
1,400,000 x, unlimited 70 None 2.80 3.79 3.79 3.79
1,399,999 x, one character to spare 70 20,000 2.80 2.80 3.79 3.79
1,400,000 x, exact fit 70 20,000 2.80 2.80 2.80 3.79
1,400,001 x, one character over 70 20,000 2.80 2.80 2.80 2.80
Base64 of 1 MiB 76 20,000 2.80 2.80 3.71 3.71
262,144 x 70 4,000 0.53 0.53 0.71 0.71
262,144 characters, trailing NBSP + y 70 4,000 0.53 0.53 0.53 0.53
262,150 characters, trailing NBSP + y, exact fit 70 3,745 0.53 0.53 0.53 0.53
100,000 x, exact fit 2 50,000 2.60 2.60 2.60 2.79
1,400,000 x followed by next 70 20,000 2.80 2.80 2.80 3.80
200 Wikipedia articles 70 3 0.62 0.62 0.62 0.62
200 Wikipedia articles 70 4,000 1.48 1.48 1.48 1.48
Peak process RSS (MB) w/ `getrusage(RUSAGE_SELF).ru_maxrss`, 5 runs
Input width max_lines main max_lines is None > >=
1,000,000 x, two lines 2 2 24.49 24.48 24.54 24.53
1,400,000 x, exact fit 70 20,000 28.20 28.21 28.31 28.23
1,400,001 x, one character over 70 20,000 28.16 28.21 28.25 28.28
100,000 x, exact fit 2 50,000 24.53 24.63 24.63 24.95
262,150 characters, trailing NBSP + y, exact fit 70 3,745 22.71 22.94 22.99 22.92

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks both. >= still leaves the "one over" case quadratic, and the NBSP rows in your table are ~10x slower than main, and the old code was ~4x slower with max_lines=None, because the split() check re-ran on every line. 80c8c53 caps the pre-split at the remaining lines instead; the rest of the word takes the old path, so the cap never changes the output.

macOS, LTO+PGO, best of 7, identical output:

wall time (ms)
Input width max_lines main before >= 80c8c53
1,400,000 x 70 None 743.6 62.5 64.8 66.6
Base64 of 1 MiB 76 None 752.0 66.9 66.7 71.8
Base64 of 1 MiB 76 20000 823.8 689.0 66.4 69.4
1,400,000 x, exact fit 70 20000 827.8 748.1 63.4 70.4
1,400,001 x, one over 70 20000 870.1 837.6 776.5 70.3
1,000,000 x 70 3 42.8 41.3 41.0 42.0
262,144 x + NBSP + y 70 None 56.2 240.8 240.8 14.6
262,144 x + NBSP + y 70 4000 56.4 58.5 243.8 14.5
262,144 x + -y 70 None 42.1 49.1 48.7 12.5
a + 262,144 \n + b, replace_whitespace=False, drop_whitespace=False 70 None 30.0 294.7 292.6 29.8
200 stdlib doc pages, one wrap() each 70 None 313.1 314.7 315.4 314.3
200 stdlib doc pages, one wrap() each 70 3 250.0 244.3 251.9 248.4
tracemalloc peak (MB)
Input max_lines main before >= 80c8c53
1,400,000 x None 2.80 3.79 3.79 3.79
Base64 of 1 MiB None 2.80 3.71 3.71 3.71
Base64 of 1 MiB 20000 2.80 2.80 3.71 3.71
1,400,000 x, exact fit 20000 2.80 2.80 3.79 3.79
1,400,001 x, one over 20000 2.80 2.80 2.80 3.79
1,000,000 x 3 2.00 2.00 2.00 2.00
262,144 x + NBSP + y None 0.53 0.53 0.53 0.73
262,144 x + NBSP + y 4000 0.53 0.53 0.53 0.73
262,144 x + -y None 0.53 0.53 0.53 0.73
a + 262,144 \n + b, replace_whitespace=False, drop_whitespace=False None 0.53 0.53 0.53 0.53
200 stdlib doc pages, one wrap() each None 9.42 9.42 9.42 9.42
200 stdlib doc pages, one wrap() each 3 3.36 3.36 3.36 3.36

Comment thread Lib/textwrap.py Outdated
# time would copy the rest of the word each time.
word = chunks[-1]
if (lines and self.max_lines is None and self.break_long_words and
0 < width < len(word) and

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is width == 0 possible in a non-degenerate case? If not, I'd just as soon see width < len(word).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, when subsequent_indent is as wide as width or wider. Without it range() gets a zero or negative step (ValueError / IndexError). Added a test.

A word that failed the whitespace check re-ran split() on the rest of
the word for every line, which was slower than main.  Pre-split only the
pieces before the first whitespace or hyphen, and only as many as the
remaining max_lines can show; the rest of the word keeps the old path.
@thejesh23

thejesh23 commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

@maurycy @sirosen thanks for your detailed review , this ended up bigger change than I initially thought but also huge perf gain , As textWrap is pure old core python I would also ask @serhiy-storchaka to review as he did the some major changes in this lib.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants