Skip to content

Simple AST level Optimization that would have ~1.5-2.5% gains for certain tests #134767

Closed as not planned
@GanerCodes

Description

@GanerCodes

Feature or enhancement

Proposal:

If we collapse statements of the form:

X = expr
X = expr that immediately and only once references X (i.e. X.a or X().y+2)

we can compose the RHS of the first line into the second line, i.e.
X = y() ; X = X.k()**2X = y().k()**2

Test (Ryzen 7 3800X, locked to 1 core, Python 3.13.3, no FT/JIT) sees f2 being ~2% faster than f1

import timeit

class B:
    def __init__(self):
        self.c = 42
class A:
    def __init__(self):
        self.b = B()

def f1():
    a = A()
    return a.b.c

def f2():
    a = A()
    a = a.b
    return a.c

number = 100_000_000
for _ in range(25):
    t1 = timeit.timeit('f1()', globals=globals(), number=number)
    t2 = timeit.timeit('f2()', globals=globals(), number=number)
    print(f'{t1:.9f} {t2:.9f}{(t2/t1-1)*100:.9f}%')

We observe the slightly larger bytecode output (68 vs 64 instr):
Image

Has this already been discussed elsewhere?

I don't think

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions