-
-
Notifications
You must be signed in to change notification settings - Fork 37.3k
Speed up pattern matching via shared checks #158687
Copy link
Copy link
Open
Labels
3.16new features, bugs and security fixesnew features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagePerformance or resource usagetype-featureA feature request or enhancementA feature request or enhancement
Description
Activity
Metadata
Metadata
Assignees
Labels
3.16new features, bugs and security fixesnew features, bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagePerformance or resource usagetype-featureA feature request or enhancementA feature request or enhancement
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:
Here, every case checks that
eventis a mapping and looks up the same two keys. If thetypevalue 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
typestrings 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.