Skip to content

textwrap: wrapping a long word takes quadratic time #161977

Open

Description

@thejesh23

Bug report

Bug description:

textwrap.wrap() takes quadratic time on a single long word. TextWrapper._handle_long_word() breaks off one line's worth of the word at a time and stores the rest with reversed_chunks[-1] = chunk[end:], which copies the whole rest of the word for every output line.

import textwrap, time
for n in (400_000, 800_000, 1_600_000, 3_200_000):
    t = time.perf_counter()
    textwrap.wrap('x' * n, 70)
    print(f'{n:>9,} chars: {time.perf_counter() - t:.2f}s')

Doubling the length makes it about four times slower:

word length time
400,000 37.6 ms
800,000 107.0 ms
1,600,000 343.2 ms
3,200,000 1252.4 ms

This is a different cause from bpo-22687 (gh-66877), which fixed the word-splitting regex.

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. added
    stdlibStandard Library Python modules in the Lib/ directory
    type-featureA feature request or enhancement
    performancePerformance or resource usage
    on Nov 14, 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

    performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions