Skip to content

gh-145860: Eliminate unnecessary refcount operations in BUILD_INTERPOLATION and BUILD_TEMPLATE#148201

Open
Siyet wants to merge 2 commits intopython:mainfrom
Siyet:gh-145860-build-interpolation-steal-refs
Open

gh-145860: Eliminate unnecessary refcount operations in BUILD_INTERPOLATION and BUILD_TEMPLATE#148201
Siyet wants to merge 2 commits intopython:mainfrom
Siyet:gh-145860-build-interpolation-steal-refs

Conversation

@Siyet
Copy link
Copy Markdown

@Siyet Siyet commented Apr 7, 2026

BUILD_INTERPOLATION and BUILD_TEMPLATE called _PyInterpolation_Build and
_PyTemplate_Build respectively, which incremented the reference counts of
their arguments via Py_NewRef. The bytecode handlers then immediately
decremented those same references via PyStackRef_CLOSE. This incref/decref
pair is redundnat.

All other BUILD instructions (BUILD_TUPLE, BUILD_LIST, BUILD_SET,
BUILD_MAP) already avoid this overhead by using "steal" semantics, where the
called function takes ownership of the references directly.

This change makes _PyInterpolation_Build and _PyTemplate_Build steal
references to their arguments (even on failure, handling cleanup internally),
and updates the bytecoed handlers to pass owned references via
PyStackRef_AsPyObjectSteal instead of borrowing and closing. The two internal
callers of _PyTemplate_Build in templateobject.c (template_new,
template_concat_templates) are updated accordingly.

This is a pure optimization with no semantic change. Reduces the number of
atomic refcount operations per BUILD_INTERPOLATION by 6 (3 incref + 3 decref)
and per BUILD_TEMPLATE by 4 (2 incref + 2 decref).

…ATION/BUILD_TEMPLATE

Make _PyInterpolation_Build and _PyTemplate_Build steal references to
their arguments instead of borrowing and incref'ing them. This avoids
redundant incref/decref pairs in the bytecode handlers, matching the
pattern already used by all other BUILD instructions.
Add comments to _PyInterpolation_Build and _PyTemplate_Build
declarations in pycore_interpolation.h and pycore_template.h.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant