Im doing some micro-benchmarks of the match statement.
The following comparison shows two functionally equivalent functions of the class matching pattern in the match statement.
classDriver:
def__init__(self, name, team, **extra):
self.name=nameself.team=teamself.extra=extradefbench_class_matching_statement():
drivers= [
Driver(name="Max Verstappen", team="Red Bull", ),
Driver(name="Sergio Perez", team="Red Bull", ),
Driver(name="Charles Leclerc", team="Ferrari", ),
Driver(name="Lewis Hamilton", team="Mercedes", ),
]
for_inrange(100_000):
fordriverindrivers:
matchdriver:
caseDriver(name="Max Verstappen"): desc=f"Max Verstappen, the current world #1"caseDriver(name=name, team="Ferrari"): desc=f"{name}, a Ferrari driver!! 🐎"caseDriver(name=name, team=team): desc=f"{name}, a {team} driver."case _: desc="Invalid request"# print(desc)defbench_class_matching_logical():
drivers= [
Driver(name="Max Verstappen", team="Red Bull", ),
Driver(name="Sergio Perez", team="Red Bull", ),
Driver(name="Charles Leclerc", team="Ferrari", ),
Driver(name="Lewis Hamilton", team="Mercedes", ),
]
for_inrange(100_000):
fordriverindrivers:
ifnotisinstance(driver, Driver):
desc="Invalid request"elifdriver.name=="Max Verstappen":
desc=f"Max Verstappen, the current world #1"elifdriver.team=="Ferrari": desc=f"{driver.name}, a Ferrari driver!! 🐎"else:
desc=f"{driver.name}, a {driver.team} driver."# print(desc)Python 3.11 executes bench_class_matching_statement() at 4x the execution time of bench_class_matching_logical()
Python 3.10 executes bench_class_matching_statement() at 2.5x the execution time of bench_class_matching_logical()
Python 3.11b1 is showing a speedup of both functions (which is great).
Pattern matching for sequences and mapping is faster than the equivalent Python code, but for classes it is significantly slower.
Im doing some micro-benchmarks of the
matchstatement.The following comparison shows two functionally equivalent functions of the class matching pattern in the
matchstatement.Python 3.11 executes
bench_class_matching_statement()at 4x the execution time ofbench_class_matching_logical()Python 3.10 executes
bench_class_matching_statement()at 2.5x the execution time ofbench_class_matching_logical()Python 3.11b1 is showing a speedup of both functions (which is great).
Pattern matching for sequences and mapping is faster than the equivalent Python code, but for classes it is significantly slower.