Skip to content

Instantly share code, notes, and snippets.

@geniusnhu
Created September 1, 2021 03:41
Show Gist options
  • Save geniusnhu/18fdc5f6b21b388d5f6fea78af7ff2eb to your computer and use it in GitHub Desktop.
Save geniusnhu/18fdc5f6b21b388d5f6fea78af7ff2eb to your computer and use it in GitHub Desktop.
Comparing class with and without __slots__
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
@JordyCuan
Copy link

I think there is a typo on line 33. Guess it should be w_slots instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment