Last active
December 26, 2022 14:19
-
-
Save misgeatgit/31fd8e863764574276c284711b20e108 to your computer and use it in GitHub Desktop.
Performance comparison of slotted vs non-slotted class in python3.11. Based on https://www.youtube.com/watch?v=Fot3_9eDmOs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3.11 | |
from typing import Union | |
from functools import partial | |
import timeit | |
class Foo: | |
__slots__ = "name", "age" | |
def __init__(self, name : str, age : int) -> None: | |
self.name = name | |
age = age | |
class FooNoSlot: | |
def __init__(self, name : str, age : int) -> None: | |
self.name = name | |
age = age | |
f = Foo(name="Foo", age=35) | |
fns = FooNoSlot(name="Foo", age=35) | |
def crud(f : Union[Foo, FooNoSlot]): | |
f.name = "Test" | |
f.name | |
del f.name | |
t1 = min(timeit.repeat(partial(crud, f), repeat=10, number=10000)) | |
t2= min(timeit.repeat(partial(crud, fns), repeat=10, number=10000)) | |
print(f"Slotted performed {t2/t1 -1:.2%} better.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment