Closed as not planned
Closed as not planned
Description
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)
def test(var):
if var:
return True
else:
return False
Bytecode:
8 0 RESUME 0
9 2 LOAD_FAST 0 (var)
4 POP_JUMP_IF_FALSE 1 (to 8)
10 6 RETURN_CONST 1 (True)
12 >> 8 RETURN_CONST 2 (False)
Ternary Operator (Less Efficient)
def test2(var):
return True if var else False
Bytecode:
14 0 RESUME 0
15 2 LOAD_FAST 0 (var)
4 POP_JUMP_IF_FALSE 2 (to 10)
6 LOAD_CONST 1 (True)
8 RETURN_VALUE
>> 10 LOAD_CONST 2 (False)
12 RETURN_VALUE
Problem
In the ternary operator version:
LOAD_CONST
is used instead of the more efficientRETURN_CONST
- This results in an additional
RETURN_VALUE
instruction - Leads to slightly increased bytecode complexity and potential performance overhead
Recommendation
Modify the bytecode generation for ternary expressions to:
- Use
RETURN_CONST
when returning boolean constants - Minimize additional instructions
- Align bytecode generation with the efficiency of traditional if-else statements
Additional Notes
- This is a micro-optimization
- Impact may vary across different Python versions
- Primarily of interest to performance-critical code paths
CPython versions tested on:
3.12
Operating systems tested on:
Linux