How python uses _ _ slots__ to reduce memory overhead
This article will explain in detail how python uses _ _ slots__ to reduce memory overhead. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
Use _ _ slots__ to reduce memory overhead.
Have you ever observed that your Python application consumes a lot of resources, especially memory? This is a technique for using class variables to reduce memory overhead to some extent.
Import sysclass FileSystem (object): def _ init__ (self, files, folders, devices): self.files = files self.folders = folders self.devices = devicesprint (sys.getsizeof (FileSystem)) class FileSystem1 (object): _ _ slots__ = ['files',' folders', 'devices'] def _ init__ (self, files, folders Devices): self.files = files self.folders = folders self.devices = devicesprint (sys.getsizeof (FileSystem1)) # In Python 3.5-> 1016-> 888
Obviously, you can see some savings in memory usage from the results. But when the memory overhead of a class is unnecessarily large, you should use _ _ slots__. Do this only after analyzing the application. Otherwise, you will make the code difficult to change and have no real benefits.
This is the end of the article on "how python uses _ _ slots__ to reduce memory overhead". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.