Skip to content

Cache the match object in the compiled re pattern #153161

Description

@serhiy-storchaka

Feature or enhancement

Proposal:

re allocates a new match object for every successful match. Matches of one pattern all have the same size, and in a typical loop the previous match dies just before the next one is created.

Keep one dead match object in the compiled pattern and reuse it for the next match instead of allocating. This saves 15-18 ns per successful match (e.g. p.match('42') goes 89 ns → 71 ns, and the string-to-Fraction constructor gains ~6%), with no behavior change. The cache slot is accessed with atomic operations; validated with the test suite, refleak runs, and a concurrent stress test on the free-threaded build.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions