Skip to content

gh-138912: Add fast path for match class patterns without sub-patterns#144820

Open
cdce8p wants to merge 1 commit intopython:mainfrom
cdce8p:match-class-opcode-isinstance
Open

gh-138912: Add fast path for match class patterns without sub-patterns#144820
cdce8p wants to merge 1 commit intopython:mainfrom
cdce8p:match-class-opcode-isinstance

Conversation

@cdce8p
Copy link
Contributor

@cdce8p cdce8p commented Feb 14, 2026

Extracted from #139080. This builds on the work merged with 75d4839.

Add a fast path for match class patterns without any sub-patterns. This avoids creating a new (empty) tuple, pushing it to the stack and subsequently unpacking the tuple result from the MATCH_CLASS opcode again.

__
Micro benchmarks with all specializations enabled.

Micro benchmark (bare class pattern)
from timeit import timeit
setup = """
class A:
    def __init__(self, x, y):
        self.x = x
        self.y = y
a = A(1, 2)

def f1(a):
    if isinstance(a, A):
        return True
    return False

def f2(a):
    match a:
        case A():
            return True
    return False
"""
print(f"If\t{timeit("f1(a)", setup, number=10**7)}")
print(f"Match\t{timeit("f2(a)", setup, number=10**7)}")
# Before
If      0.32616550009697676
Match   0.33599245804362

# After
If      0.3079932499676943
Match   0.2534141249489039 -24.58%

If specialization disabled, the performance improvement is even better with -40.5%.


📚 Documentation preview 📚: https://cpython-previews--144820.org.readthedocs.build/

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant