Skip to content

gh-140328: Use interned versions of string constants if they're already present - #140688

Draft
albertedwardson wants to merge 27 commits into
python:mainfrom
albertedwardson:string-interning
Draft

albertedwardson wants to merge 27 commits into
python:mainfrom
albertedwardson:string-interning

Conversation

@albertedwardson

@albertedwardson albertedwardson commented Oct 27, 2025 •

Copy link
Copy Markdown
Contributor

closes #140328

intern_constants() previously only interned string constants when should_intern_string() returned true, leaving equal strings duplicated even if an interned instance already existed. This change first checks the global and per-interpreter interned string tables and reuses an existing interned string when available. This applies only to string constants that come from the codeobjects; dynamically created strings are unaffected and are still created as new objects.

This makes string interning behavior more consistent: once a string is interned, subsequent equal constants can reuse the canonical object. It may slightly reduce memory usage and improves interaction with sys.intern().

The change adds a small lookup cost when loading code objects, which may affect eval(), exec(), modules loading and similar operations.

I haven't run pyperformance yet, but I plan to provide a benchmark run once I have access to an appropriate runner. Given the limited scope of the change, I expect both the performance impact and memory savings to be relatively small but measurable.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use interned versions of string constants if they're already present

3 participants