Last active
November 6, 2018 11:25
-
-
Save barrachri/c7922df84eb171eaa45e466b1b790bce to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from collections import namedtuple | |
from sys import getsizeof | |
from typing import NamedTuple | |
test_namedtuple = namedtuple("TEST", "a b c d f") | |
a = test_namedtuple(a=1,b=2,c=3,d=4,f=5) | |
class TestSlots(): | |
__slots__ = ["a","b","c","d","f"] | |
def __init__(self): | |
self.a=1 | |
self.b=2 | |
self.c=3 | |
self.d=3 | |
self.f=3 | |
class TestClass(): | |
a=1 | |
b=2 | |
c=3 | |
d=3 | |
f=3 | |
class TestNamedTuple(NamedTuple): | |
color: str | |
mileage: float | |
automatic: bool | |
car1 = TestNamedTuple('red', 3812.4, True) | |
b = TestSlots() | |
c = TestClass() | |
d = {'a':1, 'b':2, 'c':3, 'd': 4, 'f': 5} | |
if __name__ == '__main__': | |
from timeit import timeit | |
print("========= namedtuple =========") | |
print(f"Size: {getsizeof(a)}") | |
print("with a, b, c:") | |
print(timeit("z = a.c", "from __main__ import a")) | |
print("using index:") | |
print(timeit("z = a[2]", "from __main__ import a")) | |
print("========= Class using __slots__ =========") | |
print(f"Size: {getsizeof(b)}") | |
print("with a, b, c:") | |
print(timeit("z = b.c", "from __main__ import b")) | |
print("========= Class without using __slots__ =========") | |
print(f"Size: {getsizeof(c)}") | |
print("with a, b, c:") | |
print(timeit("z = c.c", "from __main__ import c")) | |
print("========= Dictionary =========") | |
print(f"Size: {getsizeof(d)}") | |
print("with keys a, b, c:") | |
print(timeit("z = d['c']", "from __main__ import d")) | |
print("========= NamedTuple with three values =========") | |
print(f"Size: {getsizeof(car1)}") | |
print("with keys a, b, c:") | |
print(timeit("z = car1.color", "from __main__ import car1")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Those are some interesting results!
Note: I added plain tuples and I changed the NamedTuple example to have the same number of attributes & the same length (a, b, c, d, f):