Title: Quadratic `compile()` / `ast.parse()` time for modules with many f-strings (PEP 701 tokenizer `update_fstring_expr` rescans the whole remaining buffer per replacement field) · Issue #155525 · python/cpython · GitHub
Open Graph Title: Quadratic `compile()` / `ast.parse()` time for modules with many f-strings (PEP 701 tokenizer `update_fstring_expr` rescans the whole remaining buffer per replacement field) · Issue #155525 · python/cpython
X Title: Quadratic `compile()` / `ast.parse()` time for modules with many f-strings (PEP 701 tokenizer `update_fstring_expr` rescans the whole remaining buffer per replacement field) · Issue #155525 · python/cpython
Description: Bug report Bug description: Summary Since the PEP 701 f-string tokenizer landed in 3.12, parsing/compiling a module that contains many f-string replacement fields is O(n²) in the total source size, where the constant is driven by the num...
Open Graph Description: Bug report Bug description: Summary Since the PEP 701 f-string tokenizer landed in 3.12, parsing/compiling a module that contains many f-string replacement fields is O(n²) in the total source size,...
X Description: Bug report Bug description: Summary Since the PEP 701 f-string tokenizer landed in 3.12, parsing/compiling a module that contains many f-string replacement fields is O(n²) in the total source size,...
Opengraph URL: https://github.com/python/cpython/issues/155525
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Quadratic `compile()` / `ast.parse()` time for modules with many f-strings (PEP 701 tokenizer `update_fstring_expr` rescans the whole remaining buffer per replacement field)","articleBody":"# Bug report\n\n### Bug description:\n\n## Summary\n\nSince the PEP 701 f-string tokenizer landed in 3.12, parsing/compiling a module that contains many f-string replacement fields is **O(n²) in the total source size**, where the constant is driven by the number of `{...}` fields. This is pure front-end (tokenizer) time — it reproduces with `compile(src, \"\u003cx>\", \"exec\")` and `ast.parse(src)` and is unaffected by any optimization level.\n\nIt is not visible on ordinary hand-written code, but it is catastrophic for large **machine-generated** modules. A ~20 MB generated module in our codebase (~10k f-strings, up to ~230 plain `{field}`s each) compiles in:\n\n| Python | `compile()` of the 20 MB module |\n|---|---|\n| 3.9.18 | **~2.3 s** |\n| 3.12.4 | **~229 s** |\n| 3.13.5 | **~376 s** (worse) |\n\n## Environment\n\n- Reproduced on CPython **3.12.4** and **3.13.5** (Linux x86-64).\n- Confirmed by source inspection to be **present on `main` (3.14-dev)** as well (see Root cause).\n\n## Minimal reproducer\n\nDependency-free. Run under 3.11 (or 3.9) vs 3.12+ and compare — the f-string compile time roughly **quadruples each time the size doubles** on 3.12+, but only doubles on ≤3.11.\n\n```python\nimport sys, time\n\ndef gen(n_fstrings, fields_each=100):\n # one module of `n_fstrings` f-strings, each with `fields_each` PLAIN replacement fields\n # (no format-spec, no conversion, no nesting). Names need not exist -- compile() only parses.\n field = \"\".join(\"{x%d}\" % i for i in range(fields_each))\n return \"\\n\".join('s%d = f\"%s\"' % (j, field) for j in range(n_fstrings))\n\nprint(sys.version)\nprev = None\nfor n in (500, 1000, 2000, 4000):\n src = gen(n)\n t0 = time.perf_counter()\n compile(src, \"\u003cgen>\", \"exec\")\n dt = time.perf_counter() - t0\n ratio = \"\" if prev is None else \" (%.1fx for 2x size)\" % (dt / prev)\n print(\"%5d f-strings, %5.0f KB: %7.3f s%s\" % (n, len(src) / 1024, dt, ratio))\n prev = dt\n```\n\n### Observed output\n\n**Python 3.9.18 — linear (~2x per size doubling):**\n```\n500 f-strings, 298 KB: 0.199 s\n1000 f-strings, 595 KB: 0.404 s (2.0x for 2x size)\n2000 f-strings, 1190 KB: 0.787 s (1.9x for 2x size)\n4000 f-strings, 2382 KB: 1.573 s (2.0x for 2x size)\n```\n\n**Python 3.12.4 — quadratic (~4x per size doubling):**\n```\n500 f-strings, 298 KB: 0.592 s\n1000 f-strings, 595 KB: 2.109 s (3.6x for 2x size)\n2000 f-strings, 1190 KB: 8.484 s (4.0x for 2x size)\n4000 f-strings, 2382 KB: 32.497 s (3.8x for 2x size)\n```\n\nSo the *same* 2.4 MB source is **~21x slower on 3.12 than 3.9** (1.57 s → 32.5 s), and the gap keeps widening with size.\n\nFor comparison, rewriting the f-strings to `str.format()` (same source size) stays linear/fast on 3.12 (~0.78 s at the 4000 row) — i.e. the cost is specifically in the f-string tokenization path.\n\n## Root cause\n\nThe PEP 701 tokenizer buffers each f-string replacement-field expression by copying from the current cursor to the **end of the remaining source buffer** on every relevant token, using `strlen(tok->cur)` + `strncpy(..., tok->cur, size)`:\n\n**3.12.4 — `Parser/tokenizer.c`, `update_fstring_expr()`:**\n```c\nstatic int\nupdate_fstring_expr(struct tok_state *tok, char cur)\n{\n Py_ssize_t size = strlen(tok->cur); // \u003c-- length to END OF BUFFER, not end of expr\n tokenizer_mode *tok_mode = TOK_GET_MODE(tok);\n switch (cur) {\n case 0:\n ...\n strncpy(tok_mode->last_expr_buffer + tok_mode->last_expr_size, tok->cur, size); // O(remaining)\n ...\n case '{':\n ...\n tok_mode->last_expr_buffer = PyMem_Malloc(size);\n ...\n strncpy(tok_mode->last_expr_buffer, tok->cur, size); // O(remaining)\n ...\n case '}': case '!': case ':':\n if (tok_mode->last_expr_end == -1) {\n tok_mode->last_expr_end = strlen(tok->start); // O(remaining)\n }\n ...\n }\n}\n```\n\nIt is called once per `{` / `}` / `!` / `:` inside an f-string. Because `size = strlen(tok->cur)` is the distance to EOF, each replacement field near the top of a large module scans/copies almost the entire remaining file. Summed over all fields:\n\n```\nΣ_fields remaining_bytes_after_field ≈ O(source_size × num_fields) ≈ O(n²)\n```\n\nA `perf` / `gdb` profile of the 20 MB case spends ~99% of time in `__strlen_evex` / `__strncpy_evex` reached from `update_fstring_expr`.\n\n**The same code (whole-remaining-buffer `strlen(tok->cur)` + `strncpy`) is still present, just relocated/renamed, in every current branch:**\n\n- 3.12: `Parser/tokenizer.c:466` — `update_fstring_expr` (`strlen(tok->cur)` @470, `strncpy` @487/@500)\n- 3.13: `Parser/lexer/lexer.c:176` — `_PyLexer_update_fstring_expr` (`strlen(tok->cur)` @180)\n- main (3.14-dev): `Parser/lexer/string.c:124` — `_PyLexer_update_ftstring_expr` (`strlen(tok->cur)` @128, `strncpy` @145/@158)\n\n### Possible direction (for maintainers to evaluate)\n\n`update_fstring_expr` runs **unconditionally** for every field, but the buffer it builds (`last_expr_buffer`) appears to be consumed only by `set_fstring_expr()` to produce the `=` self-documenting-expression debug metadata — and `set_fstring_expr()` early-returns unless `tok_mode->f_string_debug` is set. So:\n\n1. In the common case (`f_string_debug == 0`, i.e. no `=` specifier — which is the vast majority of f-strings, and all of the generated code above), the whole per-field `strlen`/`strncpy` work is discarded. Gating `update_fstring_expr` on `f_string_debug` would make that case linear.\n2. Even when debug *is* used, the copy is sized to `strlen(tok->cur)` (to EOF) rather than to the actual expression length; capturing only the expression span (start already known; end set on `}`/`:`/`!`) would remove the quadratic factor there too.\n\n## Not a duplicate of\n\n- **gh-97912** (quadratic in number of local variables / `nlocals²`) — different mechanism, in the compiler not the tokenizer, and fixed before 3.12.0. Setting `optimize=2` does not help here.\n- **gh-119118** (`tokenize.generate_tokens()` performance regression in 3.12) — that is the **pure-Python `tokenize` API** and a different trigger (one huge single-line dict). This report is the **C tokenizer used by `compile()` / `ast.parse()`**, triggered by many f-string replacement fields via `update_fstring_expr`. (Similar \"3.12 tokenizer change + generated input + repeated scan → superlinear\" shape, hence worth cross-referencing as precedent, but a distinct code path.)\n\n\n### CPython versions tested on:\n\n3.12\n\n### Operating systems tested on:\n\nLinux\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-156756\n* gh-157828\n* gh-157829\n* gh-157830\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/Seph1H0rse","@type":"Person","name":"Seph1H0rse"},"datePublished":"2026-08-11T02:30:35Z","url":"https://github.com/python/cpython/issues/155525"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:c5b78abc-11aa-f5a6-b13d-f70f35f0c430 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | BCBC:97D39:CBA669:10D017C:6B01FA6A |
| html-safe-nonce | 3c9836868ca829db8e20e99724f0327dd4108159034a350d7ff4e755c84903c6 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCQ0JDOjk3RDM5OkNCQTY2OToxMEQwMTdDOjZCMDFGQTZBIiwidmlzaXRvcl9pZCI6IjgxMDc4OTQxMDk0NDcxMTI3NCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 8380b7c6cad43206c452ba638e5fe7a89ed754e65d13066c5e5dd04a0315683a |
| hovercard-subject-tag | issue:5116083076 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/155525/issue_layout |
| twitter:image | https://opengraph.githubassets.com/496f44fa2de9ad4c366fba07aab4334d5522d70580d4b666654334be17d45401/python/cpython/issues/155525 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/496f44fa2de9ad4c366fba07aab4334d5522d70580d4b666654334be17d45401/python/cpython/issues/155525 |
| og:image:alt | Bug report Bug description: Summary Since the PEP 701 f-string tokenizer landed in 3.12, parsing/compiling a module that contains many f-string replacement fields is O(n²) in the total source size,... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | Seph1H0rse |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width