Tips to reduce Python object size
Last Updated :
24 Apr, 2020
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.
Using built-in Dictionaries:
We all are very familiar with
dictionary data type in Python. It's a way of storing data in form of keys and values. But when it comes to memory management, dictionary isn't the best. In fact, it's the worst. Let's see this with an example:
Python3 1==
# importing the sys library
import sys
Coordinates = {'x':3, 'y':0, 'z':1}
print(sys.getsizeof(Coordinates))
We see that one instance of the data type dictionary takes 288 bytes. Hence it will consume ample amount of memory when we will have many instances:

So, we conclude that dictionary is not suitable when dealing with memory-efficient programs.
Using tuples:
Tuples are perfect for storing immutable data values and is also quite efficient as compared to dictionary in reducing memory usage:
Python3 1==
import sys
Coordinates = (3, 0, 1)
print(sys.getsizeof(Coordinates))
For simplicity, we assumed that the indices
0, 1, 2 represent
x, y, z respectively. So from 288 bytes, we came down to 72 bytes by just using tuple instead of dictionary. Still it's not very efficient. If we have large number of instances, we would still require large memory:
Using class:
By arranging the code inside classes, we can significantly reduce memory consumption as compared to using dictionary and tuple.
Python3 1==
import sys
class Point:
# defining the coordinate variables
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
Coordinates = Point(3, 0, 1)
print(sys.getsizeof(Coordinates))
We see that the same program now requires 56 bytes instead of the previous 72 bytes. The variables x, y and z consume 8 bytes each while the rest 32 bytes are consumed by the inner codes of Python. If we have a larger number of instances, we have the following distribution -

So we conclude that classes have an upper-hand than dictionary and tuple when it comes to memory saving.
Side Note : Function sys.getsizeof(object[, default]) specification says: "Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to."
So in your example:
Python3 1==
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
Coordinates = Point(3, 0, 1)
the effective memory usage of object Coordinates is:
sys.getsizeof(Coordinates) +
sys.getsizeof(Coordinates.x) +
sys.getsizeof(Coordinates.y) +
sys.getsizeof(Coordinates.z) =
= 56 + 28 + 24 + 28 =
= 136
Please refer
https://docs.python.org/3/library/sys.html.
Using recordclass:
Recordclass
is a fairly new Python library. It comes with the support to record types which isn't in-built in Python. Since
recordclass
is a third-party module licensed by MIT, we need to install it first by typing this into the terminal:
pip install recordclass
Let's use
recordclass
to see if it further helps in reducing memory size.
Python3 1==
# importing the installed library
import sys
from recordclass import recordclass
Point = recordclass('Point', ('x', 'y', 'z'))
Coordinates = Point(3, 0, 1)
print(sys.getsizeof(Coordinates))
Output:
48
So the use of
recordclass
further reduced the memory required of one instance from 56 bytes to 48 bytes. This will be the distribution if we have large number of instances:
Using dataobjects:
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.
Python3 1==
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.
Similar Reads
pickle â Python object serialization
Python is a widely used general-purpose, high-level programming language. In this article, we will learn about pickling and unpickling in Python using the pickle module. The Python Pickle ModuleThe pickle module is used for implementing binary protocols for serializing and de-serializing a Python ob
9 min read
Convert Object to String in Python
Python provides built-in type conversion functions to easily transform one data type into another. This article explores the process of converting objects into strings which is a basic aspect of Python programming.Since every element in Python is an object, we can use the built-in str() and repr() m
2 min read
How to find size of an object in Python?
In python, the usage of sys.getsizeof() can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself. Note: Only the memory consumption directly attributed t
2 min read
Python object
In Python, an object is an instance of a class, which acts as a blueprint for creating objects. Each object contains data (variables) and methods to operate on that data. Python is object-oriented, meaning it focuses on objects and their interactions. For a better understanding of the concept of obj
4 min read
Collections.UserList in Python
Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a
2 min read
Unexpected Size of Python Objects in Memory
In this article, we will discuss unexpected size of python objects in Memory. Python Objects include List, tuple, Dictionary, etc have different memory sizes and also each object will have a different memory address. Unexpected size means the memory size which we can not expect. But we can get the s
2 min read
How to Change the Font Size in Python Shell?
In this article, we will see how to Change the Font Size in Python Shell Follow these steps to change font size: Step 1: Open the Python shell Python Shell Step 2: Click on the Options and select Configure IDLE Step 3: In Fonts/Tabs tab set Size value Step 4: Let's select a size value is 16 and clic
1 min read
Python | shutil.get_terminal_size() method
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Pythonâs standard utility modules. This module helps in automating process of copying and removal of files and directories. shutil.get_terminal_size() method tells the size of t
1 min read
How to get file size in Python?
We can follow different approaches to get the file size in Python. It's important to get the file size in Python to monitor file size or in case of ordering files in the directory according to file size. Method 1: Using getsize function of os.path module This function takes a file path as an argume
3 min read
Collections.UserDict in Python
An unordered collection of data values that are used to store data values like a map is known as Dictionary in Python. Unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Note: For mo
2 min read