-
-
Notifications
You must be signed in to change notification settings - Fork 31.8k
Performance Overhead in Ternary Operator Due to Value Loading vs Constant Loading #127685
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
cc @markshannon |
Question: is this the result with a DEBUG build? or PGO build? |
@picnixz This is not a special build, but just python3. 12 from uv. Python version -- 3.12.7 |
I think that this is a known problem (but I cannot find the needed issue). |
PGO/LTO/BOLT/Debug builds doesn't affect the actual bytecode construction. There's no more a |
FYI, here's the bytecode of eclips4@nixos ~/p/p/cpython (remove-ast-optimizer)> ./python
Python 3.14.0a2+ (heads/remove-ast-optimizer-dirty:7ce21584115, Jan 1 1980, 00:00:00) [GCC 13.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> def test(var):
... if var:
... return True
... else:
... return False
...
>>> dis.dis(test)
1 RESUME 0
2 LOAD_FAST 0 (var)
TO_BOOL
POP_JUMP_IF_FALSE 2 (to L1)
3 LOAD_CONST 0 (True)
RETURN_VALUE
5 L1: LOAD_CONST 1 (False)
RETURN_VALUE
>>> def test2(var):
... return True if var else False
...
>>> dis.dis(test2)
1 RESUME 0
2 LOAD_FAST 0 (var)
TO_BOOL
POP_JUMP_IF_FALSE 2 (to L1)
LOAD_CONST 0 (True)
RETURN_VALUE
L1: LOAD_CONST 1 (False)
RETURN_VALUE
>>> |
Bug report
Bug description:
A performance bottleneck has been identified in CPython's bytecode generation for ternary expressions compared to traditional if-else statements, specifically related to how constants are loaded.
Bytecode Comparison
Traditional If-Else (Optimized)
Bytecode:
Ternary Operator (Less Efficient)
Bytecode:
Problem
In the ternary operator version:
LOAD_CONST
is used instead of the more efficientRETURN_CONST
RETURN_VALUE
instructionRecommendation
Modify the bytecode generation for ternary expressions to:
RETURN_CONST
when returning boolean constantsAdditional Notes
CPython versions tested on:
3.12
Operating systems tested on:
Linux
The text was updated successfully, but these errors were encountered: