Skip to content

Performance Overhead in Ternary Operator Due to Value Loading vs Constant Loading #127685

Description

@ashm-dev

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 efficient RETURN_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

No activity

Activity on this issue will appear here.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagetype-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions