Skip to content

[3.14] gh-146455: Fix O(N²) in add_const() after constant folding moved to CFG (GH-146456) - #149011

Merged
Eclips4 merged 1 commit into
python:3.14from
miss-islington:backport-5d41632-3.14
Apr 26, 2026
Merged

Eclips4 merged 1 commit into
python:3.14from
miss-islington:backport-5d41632-3.14

Conversation

@miss-islington

@miss-islington miss-islington commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

The add_const() function in flowgraph.c uses a linear search over the
consts list to find the index of a constant. After gh-126835 moved
constant folding from the AST optimizer to the CFG optimizer, this
function is now called N times for N inner tuple elements during
fold_tuple_of_constants(), resulting in O(N²) total time.

Fix by maintaining an auxiliary _Py_hashtable_t that maps object
pointers to their indices in the consts list, providing O(1) lookup.

For a file with 100,000 constant 2-tuples:

  • Before: 10.38s (add_const occupies 83.76% of CPU time)
  • After: 1.48s
    (cherry picked from commit 5d41632)

Co-authored-by: zSirius 107359899+zSirius@users.noreply.github.com

…d to CFG (pythonGH-146456)

The add_const() function in flowgraph.c uses a linear search over the
consts list to find the index of a constant. After pythongh-126835 moved
constant folding from the AST optimizer to the CFG optimizer, this
function is now called N times for N inner tuple elements during
fold_tuple_of_constants(), resulting in O(N²) total time.

Fix by maintaining an auxiliary _Py_hashtable_t that maps object
pointers to their indices in the consts list, providing O(1) lookup.

For a file with 100,000 constant 2-tuples:
- Before: 10.38s (add_const occupies 83.76% of CPU time)
- After:  1.48s
(cherry picked from commit 5d41632)

Co-authored-by: zSirius <107359899+zSirius@users.noreply.github.com>
@python-cla-bot

python-cla-bot Bot commented Apr 26, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@Eclips4
Eclips4 merged commit 78c5e54 into python:3.14 Apr 26, 2026
49 checks passed
@miss-islington
miss-islington deleted the backport-5d41632-3.14 branch April 26, 2026 15:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants