Optimization: Avoid taking reference for trivial constant returns

* We need to take a more full decision of what's immortal for best results
This commit is contained in:
Kay Hayen
2025-11-11 12:39:20 +00:00
parent 230809c1ef
commit eab7f9a374
2 changed files with 21 additions and 2 deletions

View File

@@ -335,6 +335,19 @@ def isCompileTimeConstantValue(value):
return False
if python_version < 0x3C0:
def isConstantImmortal(value):
# Not happening before 3.12, pylint: disable=unused-argument
return False
else:
def isConstantImmortal(value):
# TODO: Add way more than these few ones.
return value in (True, False, None)
# Shared empty values, it would cost time to create them locally.
the_empty_dict = {}
the_empty_list = []

View File

@@ -9,6 +9,7 @@ by a try statement is accessible this way.
"""
from nuitka.Constants import isConstantImmortal
from nuitka.PythonVersions import python_version
from .CodeHelpers import generateExpressionCode
@@ -59,9 +60,11 @@ def generateReturnConstantCode(statement, emit, context):
emit("CHECK_OBJECT(%s);" % return_value_name)
emit("Py_DECREF(%s);" % return_value_name)
constant = statement.getConstant()
return_value_name.getCType().emitAssignmentCodeFromConstant(
to_name=return_value_name,
constant=statement.getConstant(),
constant=constant,
may_escape=True,
emit=emit,
context=context,
@@ -70,7 +73,10 @@ def generateReturnConstantCode(statement, emit, context):
if context.needsCleanup(return_value_name):
context.removeCleanupTempName(return_value_name)
else:
emit("Py_INCREF(%s);" % return_value_name)
if isConstantImmortal(constant):
emit("Py_INCREF_IMMORTAL(%s);" % return_value_name)
else:
emit("Py_INCREF(%s);" % return_value_name)
getGotoCode(label=context.getReturnTarget(), emit=emit)