Python uses automatic memory management via garbage collection to reclaim memory occupied by objects that are no longer in use, freeing resources for reuse.
Garbage Collection Mechanism:
gc
Module:
gc
module provides interfaces to the underlying garbage collector, allowing manual control over garbage collection behavior.import gc
# Disable automatic garbage collection
gc.disable()
Memory profiling helps identify memory-intensive parts of your code, memory leaks, and areas for optimization.
memory_profiler
:
memory_profiler
package allows you to profile memory usage line by line in Python programs.pip install memory_profiler
# script.py
from memory_profiler import profile
@profile
def my_function():
a = [1] * (10**6)
b = [2] * (2 * 10**7)
del b
return a
if __name__ == '__main__':
my_function()
Memory Efficient Algorithms: Choose algorithms that minimize memory usage and optimize runtime complexity for specific tasks.
Caching and memoization are techniques to store computed results for future use, improving performance by avoiding redundant computations.
functools.lru_cache
:
lru_cache
decorator in the functools
module caches the results of a function with a specified maximum size. It’s useful for functions with expensive computations that are repeatedly called with the same arguments.Example using lru_cache
:
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# Usage:
print(fibonacci(10)) # Output: 55 (computed once, cached for subsequent calls)