Memory Optimization
Memory Efficiency Strategies
Minimizing Object Creation
## Inefficient approach
def inefficient_method():
result = []
for i in range(10000):
result.append(i * 2)
return result
## Memory-efficient approach
def memory_efficient_method():
return (i * 2 for i in range(10000)) ## Generator expression
Using Appropriate Data Structures
graph TD
A[Data Structure Selection] --> B{Memory Efficiency}
B --> |Small Collections| C[List]
B --> |Large Datasets| D[NumPy Array]
B --> |Key-Value Mapping| E[Dictionary]
B --> |Unique Elements| F[Set]
Memory-Efficient Data Structures Comparison
Data Structure |
Memory Usage |
Best Use Case |
List |
High |
Dynamic collections |
Tuple |
Low |
Immutable sequences |
Set |
Moderate |
Unique elements |
NumPy Array |
Compact |
Numerical computations |
Memory Profiling Techniques
Using memory_profiler
import memory_profiler
@memory_profiler.profile
def analyze_memory_usage():
large_data = [x for x in range(1000000)]
return large_data
Tracking Memory Consumption
import sys
def check_object_size():
small_list = [1, 2, 3]
large_list = [x for x in range(10000)]
print(f"Small list memory: {sys.getsizeof(small_list)} bytes")
print(f"Large list memory: {sys.getsizeof(large_list)} bytes")
Advanced Memory Management
Garbage Collection Control
import gc
## Manually control garbage collection
gc.disable() ## Disable automatic garbage collection
## Perform memory-intensive operations
gc.enable() ## Re-enable garbage collection
Memory-Efficient Iterations
## Memory-efficient iteration
def process_large_file(filename):
with open(filename, 'r') as file:
for line in file: ## Lazy loading
yield line.strip()
Optimization Techniques
Avoiding Unnecessary Copies
import copy
## Shallow copy
original_list = [1, 2, 3]
shallow_copy = original_list[:]
## Deep copy (when needed)
complex_list = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(complex_list)
At LabEx, we emphasize practical memory optimization techniques that help developers create more efficient and scalable Python applications. Our training programs focus on real-world memory management strategies.
Memory Reduction Strategies
Lazy Evaluation
## Lazy evaluation with generators
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
## Memory-efficient fibonacci sequence
fib_sequence = list(fibonacci_generator(1000))
Weak References
import weakref
class LargeObject:
def __init__(self, data):
self.data = data
## Create a weak reference
large_obj = LargeObject([1, 2, 3, 4])
weak_ref = weakref.ref(large_obj)