![]() |
Do lists of classes take up more space in memory? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Do lists of classes take up more space in memory? (/thread-25741.html) |
Do lists of classes take up more space in memory? - DreamingInsanity - Apr-10-2020 I'm going through refactoring and cleaning up my code. At the moment, I have data written to a file to store it, then later on I take the file and create two lists out of the data. One list is multiple lists of 3 rgb values: rgb = [[55,35,133],[54,75,34],[,122,186,55],[42,134,5],[22,4,145]...] and one is a list of absolute paths to the images. Each are 30,000 items longs. As I'm refactoring, to remove the use of any files, and only have one list, I thought about creating a simple class like this: class CustomImage(): #my custom image class def __init__(self, name, path, size, rgb, ext="png"): self.name = name self.path = path self.size = size self.ext = ext self.avg = rgb @property def rgb(self): return self.avg @property def size(self): return self.size @property def path(self): return self.path @property def name(self): return self.name @property def ext(self): return self.extOnce I have downloaded an image, I simply create a "CustomImage" out of that image, which I can easily use later in my code. I would store all the these "CustomImages" in a list (also of 30,000 items) What would be most likely to take up more memory? I would test it but I'm not sure about how I can measure list sizes in memory. Found out how to test it: The two lists take up a total of 507,248 bytes in memory. The class, which has become: class CustomImage(): #my custom image class def __init__(self, name, path, size, rgb, ext="png"): self.name = name self.path = path self.size = size self.ext = ext self.avg = rgbtakes up only 253,624 bytes in an array of 30,000 RE: Do lists of classes take up more space in memory? - deanhystad - Apr-10-2020 Since each image always has the same attributes, you could save even more space using slots. Classes that use slots instead of __dict___ provide faster access and have a smaller memory footprint. class CustomImage(): #my custom image class __slots__ = 'name', 'path', 'size', 'ext', 'avg' def __init__(self, name, path, size, rgb, ext="png"): self.name = name self.path = path self.size = size self.ext = ext self.avg = rgbWith slots you cannot add an attribute to the class. You can access or set attribute values, but I could not do custimg.rating = 4 because there is no slot for "rating". If CustomImage is immutable you could also use a named tuple (import collections). |