How to use dataobjects In Python
In previous example, while using recordclass
, even the garbage values are collected thus wasting unnecessary memory. This means that there is still a scope of optimization. That’s exactly were dataobjects come in use. The dataobject functionality comes under the recordclass module with a specialty that it does not contribute towards any garbage values.
import sys from recordclass import make_dataclass Position = make_dataclass( 'Position' , ( 'x' , 'y' , 'z' )) Coordinates = Position( 3 , 0 , 1 ) print (sys.getsizeof(Coordinates)) |
Output:
40
Finally, we see a size reduction from 48 bytes per instance to 40 bytes per instance. Hence, we see that dataobjects are the most efficient way to organize our code when it comes to least memory utilization.
Tips to reduce Python object size
We all know a very common drawback of Python when compared to programming languages such as C or C++. It is significantly slower and isn’t quite suitable to perform memory-intensive tasks as Python objects consume a lot of memory. This can result in memory problems when dealing with certain tasks. When the RAM becomes overloaded with tasks during execution and programs start freezing or behaving unnaturally, we call it a Memory problem.
Let’s look at some ways in which we can use this memory effectively and reduce the size of objects.