Day 9: Python Memory Management - How Python Handles Memory Efficiently

Python has automatic memory management, but understanding how it works can improve performance and prevent memory leaks. Let's explore Garbage Collection, Reference Counting, and Memory Optimization techniques!


1?? Reference Counting - How Objects are Tracked

Python uses reference counting to track how many variables refer to an object. If the reference count drops to zero, the memory is freed

import sys

x =  [1, 2, 3]
y=x
print(sys.getrefcount(x))
del x
print(sys.getrefcount(y))        

?? Understanding reference counting helps prevent memory leaks in large applications


2?? Garbage Collection - Automatic Cleanup

Python has a Garbage Collector (GC) that removes unreachable objects. It uses a technique called cyclic garbage collection to handle objects with circular references

# Manually triggering garbage collection

import gc

class Test:
    def __init__(self):
        print("Object Created")

    def __del__(self):
        print("Object deleted")

obj = Test()
del obj
gc.collect()        

?? Python automatically runs the garbage collector, but manual triggering may be useful for memory-intensive programs


3?? Circular References - When Reference Counting Fails

When objects reference each other, their reference count never reaches zero, causing memory leaks

import gc

class A:
    def __init__(self):
        self.ref = None
    
obj1 = A()
obj2 = A()
obj1.ref = obj2
obj2.ref = obj1

del obj1
del obj2

gc.collect()        

?? Python's GC can detect circular references and free memory, but avoiding circular references is a best practice


4?? Memory Optimization Techniques

? 1. Use slots to reduce Memory Overhead

By default, python stores attributes in a dictionary, which uses extra memory. Using slots reduces this overhead

class Person:
    __slots__ = ['name', 'age']

    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Jyothsna", 28)
print(p.name)        

Using slots saves memory, especially in applications with many objects


? Use Generators Instead of Lists

Generators do not store all elements in memory, making them efficient for large datasets

def generate_numbers():
    for i in range(1000000):
        yield i

gen =  generate_numbers()
print(next(gen))
print(next(gen))        

?? Use generators when handling large data streams to save memory


? Use del and gc.collect() When Necessary

Manually deleting objects and calling garbage collection frees up memory in long-running applications

import gc

data = [ i for i in range(100000)]
del data

gc.collect()        

?? Use in memory-intensive applications like data processing and machine learning


Summary

?? Python manages memory automatically, but knowing how it works helps write efficient code

?? Avoid circular references, use generators, and optimize memory with slots


#100DaysOfCode #Python #MemoryManagement #GarbageCollection #Performance #Coding


要查看或添加评论,请登录

Sarasa Jyothsna Kamireddi的更多文章

社区洞察

其他会员也浏览了