Created
September 1, 2021 03:41
-
-
Save geniusnhu/18fdc5f6b21b388d5f6fea78af7ff2eb to your computer and use it in GitHub Desktop.
Comparing class with and without __slots__
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
import numpy as np | |
import pandas as pd | |
import objgraph | |
### class without __slots__ | |
class PointWithDict(): | |
def __init__(self, iters): | |
self.iters = iters | |
def convert(self): | |
s = ["xyz"]*self.iters | |
s = "".join(s) | |
assert len(s) == 3*iters | |
w_dict = PointWithDict(10000) | |
objgraph.show_refs([w_dict], filename='PointWithDict_structure.png') | |
### class using __slots__ | |
class PointWithSlots(): | |
__slots__ = "iters" | |
def __init__(self, iters): | |
self.iters = iters | |
def convert(self): | |
s = ["xyz"]*self.iters | |
s = "".join(s) | |
assert len(s) == 3*iters | |
w_slots = PointWithSlots(10000) | |
objgraph.show_refs([w_slots],filename='PointWithSlots_structure.png') | |
### Check memory footprint | |
>>> print(sys.getsizeof(w_dict), sys.getsizeof(w_dict.__weakref__), sys.getsizeof(w_dict.__dict__)) | |
64 16 120 | |
>>> print(sys.getsizeof(ob)) | |
56 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think there is a typo on line 33. Guess it should be
w_slots
instead