Skip to content

gh-72902: improve Fraction(str) speed - #149024

Merged
StanFromIreland merged 5 commits into
python:mainfrom
eendebakpt:fractions_startup
Nov 30, 2026
Merged

StanFromIreland merged 5 commits into
python:mainfrom
eendebakpt:fractions_startup

Conversation

@eendebakpt

@eendebakpt eendebakpt commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Improve fractions startup time by improving the regexp and using m.groups(). Added tests have been cherry-picked from #133994 by @skirpichev

Benchmark

Benchmark ref patch
Fraction('123') 1.09 us 902 ns: 1.21x faster
Fraction('1/3') 1.12 us 946 ns: 1.18x faster
Fraction('1.2e-3') 1.66 us 1.29 us: 1.28x faster
Fraction('-.2') 1.38 us 1.05 us: 1.31x faster
Geometric mean (ref) 1.24x faster

with script

import pyperf
from fractions import Fraction as F

runner = pyperf.Runner()
s = 'Fraction'
for v in ["123", "1/3", "1.2e-3", "-.2"]:
    r = s + '(' + repr(v) + ')'
    runner.bench_func(r, F, v)
Detailed changes to the regexp 1. Possessive quantifiers (*+, ++, ?+) — match greedily, never backtrack (digits/underscores can't overlap) 2. `[eE]` instead of `re.IGNORECASE` — only `E` needed case folding 3. `\d*|\d+(_\d+)*` to `(?:\d++(?:_\d++)*+)?+` — same language, no alternation, no backtracking. 4. `/denom` branch unconditional — the other alternation branch already matches empty, so the outer ? was redundant. 5. Drop unnamed capture groups around `(_\d+)*`

(modifications found by Claude, removed a few changes to keep diff shorter)

@skirpichev

Copy link
Copy Markdown
Member

PR description looks misleading for me. I guess it's a replacement for #133994.

@eendebakpt eendebakpt changed the title gh-72902: Improve fractions startup time gh-72902: improve Fraction(str) speed Apr 27, 2026
@github-actions

Copy link
Copy Markdown

This PR is stale because it has been open for 90 days with no activity.

@github-actions github-actions Bot added the stale Stale PR or inactive for long period of time. label Aug 10, 2026
@StanFromIreland StanFromIreland changed the title gh-72902: improve Fraction(str) speed gh-72902: improve Fraction(str) speed Nov 30, 2026
@bedevere-app bedevere-app Bot added the type-feature A feature request or enhancement label Nov 30, 2026
@StanFromIreland
StanFromIreland enabled auto-merge (squash) November 30, 2026 20:22
@StanFromIreland
StanFromIreland merged commit c37d06e into python:main Nov 30, 2026
56 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale Stale PR or inactive for long period of time. type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants