0% found this document useful (0 votes)
5 views6 pages

Memory Management in Python

Memory management in Python is primarily handled by the Python Memory Manager, which includes reference counting, garbage collection, and memory pools. Reference counting tracks the number of references to an object, while the garbage collector identifies and frees circular references. Python also provides memory allocation functions and techniques to avoid memory leaks, ensuring efficient memory usage.

Uploaded by

rj0110865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views6 pages

Memory Management in Python

Memory management in Python is primarily handled by the Python Memory Manager, which includes reference counting, garbage collection, and memory pools. Reference counting tracks the number of references to an object, while the garbage collector identifies and frees circular references. Python also provides memory allocation functions and techniques to avoid memory leaks, ensuring efficient memory usage.

Uploaded by

rj0110865
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Memory management in Python is handled primarily by the Python

Memory Manager, which ensures the efficient allocation, deallocation, and


reuse of memory for Python objects. The key components of memory
management in Python are:
1. Reference Counting
Python uses a reference counting system to manage memory. Each object in
Python has a reference count, which tracks how many references point to
that object. When the reference count drops to zero, meaning no references
are pointing to the object, the memory occupied by the object is
automatically deallocated.
x = []
y = x # Reference count for the empty list increases
del x # Reference count decreases
When y is deleted or goes out of scope, the memory is freed because the
reference count reaches zero.
2. Garbage Collection
In addition to reference counting, Python has a garbage collector that
detects and frees up circular references—situations where two or more
objects refer to each other, preventing their reference counts from ever
reaching zero.
Python's garbage collector works in three generations:
 Generation 0 (new objects): Short-lived objects are allocated here.
 Generation 1 and Generation 2: Long-lived objects move to these
generations.
Objects are periodically moved between these generations based on their
lifespan, and the garbage collector runs to reclaim memory by detecting
cycles of unused objects.
import gc
gc.collect() # Manually trigger garbage collection
3. Memory Pools and Arenas
Python manages memory using pools and arenas. Small objects are
allocated from fixed-size pools, which come from larger memory blocks
called arenas. For larger objects, Python uses the underlying system’s
memory management directly.
4. Memory Allocation Functions
Python provides several memory management functions in the sys module,
such as:
 sys.getsizeof(): Returns the size of an object in bytes.
 sys.getrefcount(): Returns the reference count for an object.
 gc.collect(): Triggers garbage collection manually.
5. Avoiding Memory Leaks
Memory leaks in Python can occur if reference cycles are not properly
cleaned up or when objects that consume memory are not properly
deallocated. To avoid this:
 Use weak references from the module for large or complex objects.
 Use context managers (with statements) to handle resources like files
and network connections properly.

Garbage Collection in Python


In conventional programming languages like C++, the developers need to
manually allocate and deallocate memory(also known as dynamic memory
allocation), whereas in Python all of this process is built-in and automated
using Garbage collectors. The garbage collector is responsible for freeing up
space once the object stored in the memory is no longer of use. This is done so
that the same space can be provided to a new object that needs it at that
particular moment.
x=5
y=x

if id(x) == id(y):
print("x and y are pointing to the same memory location")
else:
print("x and y does NOT point to the same memory location")
Output
x and y are pointing to the same memory location
It is also important to note that Python also supports manual garbage collection.
There are two types of manual garbage collection:
 Time-based Garbage Collection: This is a type of manual garbage
collection where the garbage collector executes itself after a fixed interval
of time.
 Event-Based Garbage Collection: In this type of garbage collection, we
specify a particular event whose occurs triggers the garbage collector. For
instance, when you exit an application, the space occupied by the same
needs to be cleared up for further use by other objects.
 Concept of Reference Counting:
 Reference counting refers to the concept of counting the number of times
an object is referenced by other objects in the system. This count gets
altered each time a new reference to the object is added or removed.
These objects get deallocated from the memory once the reference count
reaches zero.
 For instance, consider a variable(say x), with the value (say,100). Now
the Python VM will create an object for x with the value 100 in the
private heap.
 x = 100


 Now let’s create another variable(say, y), with the value same as the
variable x.
 x= 100
 y= x


 Now doing this will make the variable y point to the original value stored
in the private heap rather than creating another object of y in the private
heap with the value 100. Just to make sure that both x and y are referring
to the same object run the below code:
x = 100
y=x

if id(x) == id(y):
print("x and y are pointing to the same object")
else:
print("x and y does NOT point to the same object")
Output:
x and y are pointing to the same object
Now that we have established that both x and y are referring to the same object
in the heap, let’s change the value of x and observer the behavior of the same
code above.
x = 100
y=x

# increment the value of x by 10


x+=10

if id(x) == id(y):
print("x and y are pointing to the same object")
else:
print("x and y does NOT point to the same object")
Output:
x and y does NOT point to the same object

This behavior is because the variables x and y are not referencing the same
object as x got changed. So now x creates a new reference object and y will still
be referencing the original value of x ie, 100.

Python Memory Allocation

Static memory allocation happens at the compile time. we declare a static array
with the fixed sizes. Memory is allocated at the time of compilation. However,
we cannot use the memory again in the further program.
1. static int a=10;
Stack Allocation
The Stack data structure is used to store the static memory. It is only needed
inside the particular function or method call. The function is added in program's
call stack whenever we call it. Variable assignment inside the function is
temporarily stored in the function call stack; the function returns the value, and
the call stack moves to the text task. The compiler handles all these processes,
def func():

# All these variables get memory


# allocated on stack
a = 20
b = []
c = ""
Dynamic Memory Allocation
Dynamic memory allocates the memory at the runtime to the program. For
example - In C/C++, there is a predefined size of the integer of float data type
but there is no predefine size of the data types. Memory is allocated to the
objects at the run time. We use the Heap for implement dynamic memory
management. We can use the memory throughout the program.
Heap Memory Allocation
Heap data structure is used for dynamic memory which is not related to naming
counterparts. It is type of memory that uses outside the program at the global
space. One of the best advantages of heap memory is to it freed up the memory
space if the object is no longer in use or the node is deleted.
# This memory for 10 integers
# is allocated on heap.
a = [0]*10

You might also like