Get the App
SLTechnology News&Howtos  ›  Servers  › 

How python uses _ _ slots__ to reduce memory overhead

Shulou Source: shulou.com Published: 2022-05-31 11:02:03 10月04日 Update

This article mainly introduces how python uses _ _ slots__ to reduce memory expenses, which has a certain reference value. Interested friends can refer to it. I hope you can learn a lot after reading this article.

Use _ _ slots__ to reduce memory overhead

Have you noticed that your Python application takes up a lot of resources, especially memory? One trick is to use the _ _ slots__ class variable to reduce memory expenditure to some extent.

Import sysclassFileSystem (object): def _ init__ (self,files,folders,devices): self.files= filesself.folders= foldersself.devices= devicesprint (sys.getsizeof (FileSystem)) classFileSystem1 (object): _ _ slots__= ['files','folders','devices'] def _ init__ (self,files,folders,devices): self.files= filesself.folders= foldersself.devices= devicesprint (sys.getsizeof (FileSystem1)) # In Python 3.531-> 1016room2-> 888

Obviously, you can see from the results that there are savings in memory usage, but you should only use _ _ slots__ when the memory overhead of a class is unnecessarily large. Use it only after performance analysis of the application, otherwise you just make the code difficult to change without real benefits.

[translator's note: the above result in my win10 python2.7 is:

# In Python 2.7win10#1- > 896 win10#1--> 1016

Therefore, this comparison method is not so convincing. _ _ slots__ is mainly used to limit the attribute information of objects. In addition, it may cost less when there are many objects generated. For more information, please see the official documentation of python:

The slots declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because dict is not created for each instance. ]

Thank you for reading this article carefully. I hope the article "how python uses _ _ slots__ to reduce memory expenses" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Memory articles objects results applications obvious code value information interests variables just at the same time official attributes overhead performance performance analysis techniques documentation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Tech Info Huawei NVidia MariaDB