Decoding Python Memory Management: Navigating Dynamic Allocation

17 Slides1.22 MB

Decoding Python Memory Management: Navigating Dynamic Allocation and Cycle Garbage Collection Zi Li

MOTIVATION Memory Management is of great significance(sometimes)

MOTIVATION Sometimes we have to solve the problem by ourselves From adjacency To adjacency list/ 链式前向星 matrix

MOTIVATION When it comes to a list How to prevent memory conflicts when appending a new element to a list? In C , we have vector. In Python, the list itself can handle that. (Automatically!)

MOTIVATION So sometimes, Python can implement memory management automatically. We’re going to introduce two ways of this. Dynamic memory allocation Cycle Garbage Collection Mechanism

DYNAMIC MEMORY ALLOCATION Dynamic arrays serve as a key example to explore dynamic allocation in Python’s memory management, particularly during operations like appending elements.

DYNAMIC MEMORY ALLOCATION The ‘id()‘ function in Python helps us understand this process by revealing the memory address of an object.

DYNAMIC MEMORY ALLOCATION If the current memory block can handle the growing list, the ‘id(a)‘ remains the same. Otherwise a new block with a different address may be created.(Seldomly)

DYNAMIC MEMORY ALLOCATION There are two parts of memory: stack memory and heap memory. List object is stored in heap memory.

CYCLE GARBAGE COLLECTION MECHANISM Circular references occur when a group of objects references each other, forming a cycle. Traditional methods may struggle.

CYCLE GARBAGE COLLECTION MECHANISM Tracking objects that are "containers“, and determining what objects in them can't be reached anywhere else. (containers are things like lists, dictionaries and custom class instances)

CYCLE GARBAGE COLLECTION MECHANISM Tracking objects that are "containers“, and determining what objects in them can't be reached anywhere else.

CYCLE GARBAGE COLLECTION MECHANISM Tracking objects that are "containers“, and determining what objects in them can't be reached anywhere else.

CYCLE GARBAGE COLLECTION MECHANISM Tracking objects that are "containers“, and determining what objects in them can't be reached anywhere else.

CYCLE GARBAGE COLLECTION MECHANISM Tracking objects that are "containers“, and determining what objects in them can't be reached anywhere else.

PYTHON MEMORY MANAGEMENT Two ways of implementation Enhanced efficiency and peak performance Address the challenge of optimal memory utilization

THANKS!

Back to top button