Skip to content

Speed up pattern matching via shared checks #158687

Description

@pablogsal

I've been playing with ways to speed up pattern matching. When several cases have the same shape, we often repeat checks and lookups that already succeeded. I think we can do better here. For example:

match event:
    case {"type": "start", "value": value}: ...
    case {"type": "stop", "value": value}: ...
    case {"type": "pause", "value": value}: ...
    case {"type": "resume", "value": value}: ...

Here, every case checks that event is a mapping and looks up the same two keys. If the type value does not match, we do those checks and lookups again for the next case.

The idea is to find consecutive cases that start with the same work and share that part. Once we have checked the mapping and read the values, we can keep them and try the different type strings in order. If one does not match, we move on to the next comparison without repeating the common work.

The same idea applies to sequences with the same shape and class patterns that read the same attributes. We would still try cases in their original order and stop at the first match. We need to be careful with guards, since they can change what the next case sees.

This seems useful for longer matches where most cases only differ in a tag or a literal value. How much it helps would depend on which cases usually match and how much work they share.

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

    3.16new features, bugs and security fixesinterpreter-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