From pympler import asizeof article = Article('2020-01-01', 'xiaoxu') articleslots = ArticleWithSlots('2020-01-01', 'xiaoxu') print(asizeof.asizeof(article)) # 416 print(asizeof.asizeof(articleslots)) # 184. Such a good performance is because articleslots doesn’t have dict attribute which actually saves a lot of memory. A lot of technical reasons are being put forward by manufacturers as to why micro SD card slots are disappearing from smartphone, especially on high-end devices. But the real reason is a lot.
In Python every class can have instance attributes. By default Pythonuses a dict to store an object’s instance attributes. This is reallyhelpful as it allows setting arbitrary new attributes at runtime.
However, for small classes with known attributes it might be abottleneck. The dict
wastes a lot of RAM. Python can’t just allocatea static amount of memory at object creation to store all theattributes. Therefore it sucks a lot of RAM if you create a lot ofobjects (I am talking in thousands and millions). Still there is a wayto circumvent this issue. It involves the usage of __slots__
totell Python not to use a dict, and only allocate space for a fixed setof attributes. Here is an example with and without __slots__
:
Without__slots__
:
With__slots__
:
The second piece of code will reduce the burden on your RAM. Some peoplehave seen almost 40 to 50% reduction in RAM usage by using thistechnique.
On a sidenote, you might want to give PyPy a try. It does all of theseoptimizations by default.
Below you can see an example showing exact memory usage with and without __slots__
done in IPython thanks to https://github.com/ianozsvald/ipython_memory_usage