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
This comment has been minimized.
dbader commentedJun 11, 2017
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):