I found that the Python 3.11.1 implementations of all()
and any()
are 30% slower and 23% slower respectively compared to Python 3.10.9
Any idea why this might be the case? (Unfortunately I don't have the skills to look through the underlying implementation of the CPython code)
import timeit
from functools import partial
import platform
def find_by_keys(
keys: list[str],
table: list[dict[str, str | int]],
match_data: dict[str, str | int],
) -> dict[str, str | int] | None:
for item in table:
if all(item[k] == match_data[k] for k in keys): # 30% slower on 3.11
# if any(item[k] == match_data[k] for k in keys): # 23% slower on 3.11
# if item["id"] == match_data["id"]: # 3% faster on 3.11
return item
return None
def main():
keys: list[str] = ["id", "key_1", "key_2"]
table: list[dict[str, str | int]] = [
{
"id": i,
"key_1": "val_1",
"key_2": "val_2",
}
for i in range(1, 5001)
]
match_data: dict[str, str | int] = {
"id": 3000,
"key_1": "val_1",
"key_2": "val_2",
}
# Note: used repeat=50000 for all() calls, otherwise used repeat=500000
timeit_output = timeit.repeat(
partial(find_by_keys, keys, table, match_data),
repeat=50000,
number=1
)
average_time = sum(timeit_output) / len(timeit_output)
best_time = min(timeit_output)
tps_output = 1 / average_time
print(f"Python version = {platform.python_version()}")
print(f"Average time = {average_time}")
print(f"Best time = {best_time}")
print(f"Average transactions per second = {tps_output}")
if __name__ == "__main__":
main()
Results
Console output using Python 3.10.9:
Python version = 3.10.9
Average time = 0.0008256170657486655
Best time = 0.0007106999401003122
Average transactions per second = 1211.2152733824669
Console output using Python 3.11.1:
Python version = 3.11.1
Average time = 0.0011819988898839802
Best time = 0.001033599954098463
Average transactions per second = 846.0244832363215