-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-memory-optimization.py
More file actions
1528 lines (1153 loc) · 49.3 KB
/
02-memory-optimization.py
File metadata and controls
1528 lines (1153 loc) · 49.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Memory Optimization Best Practices in Python
This module demonstrates various techniques for optimizing memory usage in Python applications.
Learn how to reduce memory footprint, prevent memory leaks, and write memory-efficient code.
Topics covered:
1. Understanding memory usage patterns
2. Using __slots__ for memory-efficient classes
3. Generators vs lists for large datasets
4. Memory profiling and monitoring
5. Weak references to prevent circular references
6. Memory-efficient data structures
7. Object pooling and reuse
8. Garbage collection optimization
Requirements:
1. Demonstrate memory usage measurement
2. Show __slots__ optimization
3. Compare generators vs lists memory usage
4. Implement weak references
5. Show memory-efficient data structures
6. Demonstrate object pooling
7. Show garbage collection best practices
Example usage:
# Memory-efficient class
class Point:
__slots__ = ['x', 'y']
# Generator for large datasets
def large_dataset():
for i in range(1000000):
yield i * 2
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
#
# Tips for success:
# - Read about memory optimization techniques
# - Think about when memory usage becomes critical
# - Start with simple examples
# - Test memory usage before and after optimization
# - Don't worry if it's not perfect - learning is a process!
#
# Remember: The best way to learn programming is by doing, not by reading solutions!
#
# Take your time, experiment, and enjoy the learning process!
# Try to implement your solution here:
# (Write your code below this line)
# HINT SECTION (Only look if you're really stuck!)
#
# Think about:
# - How to measure memory usage in Python?
# - What is __slots__ and when should you use it?
# - When are generators more memory-efficient than lists?
# - How do weak references help prevent memory leaks?
# - What data structures use less memory?
#
# Remember: Start simple and build up complexity gradually!
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Import modules and create memory measurement utilities
# ===============================================================================
# Explanation:
# Before optimizing memory, we need to measure it. We'll create utilities
# to track memory usage and compare different approaches.
import sys
import gc
import weakref
from typing import List, Generator, Optional, Any
from collections import deque
import tracemalloc
class MemoryProfiler:
"""Utility class for measuring memory usage."""
def __init__(self):
self.start_memory = 0
self.peak_memory = 0
def start_profiling(self):
"""Start memory profiling."""
tracemalloc.start()
gc.collect() # Clean up before measuring
self.start_memory = tracemalloc.get_traced_memory()[0]
return self
def get_current_usage(self) -> tuple:
"""Get current memory usage in bytes."""
if tracemalloc.is_tracing():
current, peak = tracemalloc.get_traced_memory()
return current, peak
return 0, 0
def stop_profiling(self) -> dict:
"""Stop profiling and return memory statistics."""
if tracemalloc.is_tracing():
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return {
'start_memory': self.start_memory,
'final_memory': current,
'peak_memory': peak,
'memory_used': current - self.start_memory,
'peak_usage': peak - self.start_memory
}
return {}
def get_object_size(obj) -> int:
"""Get the size of an object in bytes."""
return sys.getsizeof(obj)
def format_bytes(bytes_value: int) -> str:
"""Format bytes into human-readable format."""
for unit in ['B', 'KB', 'MB', 'GB']:
if bytes_value < 1024.0:
return f"{bytes_value:.2f} {unit}"
bytes_value /= 1024.0
return f"{bytes_value:.2f} TB"
# Example usage of memory profiling
def demonstrate_memory_profiling():
"""Demonstrate how to use memory profiling utilities."""
print("=== Memory Profiling Demo ===")
profiler = MemoryProfiler()
profiler.start_profiling()
# Create some objects to measure
large_list = [i for i in range(100000)]
stats = profiler.stop_profiling()
print(f"Memory used: {format_bytes(stats['memory_used'])}")
print(f"Peak memory: {format_bytes(stats['peak_usage'])}")
print(f"List size: {format_bytes(get_object_size(large_list))}")
# Step 2: Using __slots__ for memory-efficient classes
# ===============================================================================
# Explanation:
# By default, Python stores instance attributes in a dictionary (__dict__).
# __slots__ allows us to explicitly declare which attributes a class will have,
# eliminating the __dict__ and reducing memory usage significantly.
# Previous code from Step 1:
# (All imports and MemoryProfiler class from above)
class RegularPoint:
"""Regular class without __slots__ - uses more memory."""
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def distance_from_origin(self) -> float:
return (self.x ** 2 + self.y ** 2) ** 0.5
class OptimizedPoint:
"""Memory-optimized class using __slots__."""
__slots__ = ['x', 'y'] # Only these attributes allowed
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def distance_from_origin(self) -> float:
return (self.x ** 2 + self.y ** 2) ** 0.5
class ComplexRegularClass:
"""Regular class with many attributes."""
def __init__(self):
self.attr1 = "value1"
self.attr2 = "value2"
self.attr3 = 123
self.attr4 = [1, 2, 3]
self.attr5 = {"key": "value"}
class ComplexOptimizedClass:
"""Optimized class with __slots__."""
__slots__ = ['attr1', 'attr2', 'attr3', 'attr4', 'attr5']
def __init__(self):
self.attr1 = "value1"
self.attr2 = "value2"
self.attr3 = 123
self.attr4 = [1, 2, 3]
self.attr5 = {"key": "value"}
def compare_slots_memory_usage():
"""Compare memory usage between regular and __slots__ classes."""
print("\n=== __slots__ Memory Comparison ===")
# Test simple classes
regular_point = RegularPoint(1.0, 2.0)
optimized_point = OptimizedPoint(1.0, 2.0)
print(f"Regular Point size: {format_bytes(get_object_size(regular_point))}")
print(f"Optimized Point size: {format_bytes(get_object_size(optimized_point))}")
# Test with many instances
profiler = MemoryProfiler()
# Regular classes
profiler.start_profiling()
regular_points = [RegularPoint(i, i+1) for i in range(100000)]
regular_stats = profiler.stop_profiling()
# Optimized classes
profiler.start_profiling()
optimized_points = [OptimizedPoint(i, i+1) for i in range(100000)]
optimized_stats = profiler.stop_profiling()
print(f"\n100,000 Regular Points: {format_bytes(regular_stats['memory_used'])}")
print(f"100,000 Optimized Points: {format_bytes(optimized_stats['memory_used'])}")
memory_saved = regular_stats['memory_used'] - optimized_stats['memory_used']
savings_percent = (memory_saved / regular_stats['memory_used']) * 100
print(f"Memory saved: {format_bytes(memory_saved)} ({savings_percent:.1f}%)")
def demonstrate_slots_limitations():
"""Show limitations and considerations when using __slots__."""
print("\n=== __slots__ Limitations Demo ===")
# Cannot add new attributes dynamically
regular = RegularPoint(1, 2)
optimized = OptimizedPoint(1, 2)
# This works with regular class
regular.new_attr = "dynamic"
print(f"Regular class - added dynamic attribute: {regular.new_attr}")
# This would raise AttributeError with __slots__ class
try:
optimized.new_attr = "dynamic"
except AttributeError as e:
print(f"Optimized class error: {e}")
# __slots__ classes don't have __dict__ by default
print(f"Regular class has __dict__: {hasattr(regular, '__dict__')}")
print(f"Optimized class has __dict__: {hasattr(optimized, '__dict__')}")
# Step 3: Generators vs Lists for memory efficiency
# ===============================================================================
# Explanation:
# Generators are memory-efficient because they produce items on-demand rather
# than storing all items in memory at once. This is crucial for large datasets.
# Previous code from Steps 1-2:
# (All imports, MemoryProfiler, and __slots__ classes from above)
def create_large_list(size: int) -> List[int]:
"""Create a large list - stores all items in memory."""
return [i * 2 for i in range(size)]
def create_large_generator(size: int) -> Generator[int, None, None]:
"""Create a generator - produces items on demand."""
for i in range(size):
yield i * 2
def fibonacci_list(n: int) -> List[int]:
"""Generate Fibonacci sequence as a list."""
if n <= 0:
return []
elif n == 1:
return [0]
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib
def fibonacci_generator(n: int) -> Generator[int, None, None]:
"""Generate Fibonacci sequence as a generator."""
if n <= 0:
return
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
def process_data_with_list(data_size: int) -> int:
"""Process data using list comprehension."""
# Creates entire list in memory first
numbers = [i for i in range(data_size)]
squared = [x * x for x in numbers]
filtered = [x for x in squared if x % 2 == 0]
return sum(filtered)
def process_data_with_generator(data_size: int) -> int:
"""Process data using generator expressions."""
# Processes items one at a time
numbers = (i for i in range(data_size))
squared = (x * x for x in numbers)
filtered = (x for x in squared if x % 2 == 0)
return sum(filtered)
def compare_list_vs_generator_memory():
"""Compare memory usage between lists and generators."""
print("\n=== Lists vs Generators Memory Comparison ===")
size = 1000000
# Test list creation
profiler = MemoryProfiler()
profiler.start_profiling()
large_list = create_large_list(size)
list_stats = profiler.stop_profiling()
# Test generator creation
profiler.start_profiling()
large_generator = create_large_generator(size)
generator_stats = profiler.stop_profiling()
print(f"List with {size:,} items: {format_bytes(list_stats['memory_used'])}")
print(f"Generator object: {format_bytes(generator_stats['memory_used'])}")
print(f"Generator object size: {format_bytes(get_object_size(large_generator))}")
# Compare processing approaches
profiler.start_profiling()
list_result = process_data_with_list(100000)
list_process_stats = profiler.stop_profiling()
profiler.start_profiling()
generator_result = process_data_with_generator(100000)
generator_process_stats = profiler.stop_profiling()
print(f"\nProcessing with lists: {format_bytes(list_process_stats['memory_used'])}")
print(f"Processing with generators: {format_bytes(generator_process_stats['memory_used'])}")
print(f"Results are equal: {list_result == generator_result}")
def demonstrate_generator_benefits():
"""Show practical benefits of generators."""
print("\n=== Generator Benefits Demo ===")
# Memory usage for Fibonacci sequences
n = 10000
profiler = MemoryProfiler()
profiler.start_profiling()
fib_list = fibonacci_list(n)
list_stats = profiler.stop_profiling()
profiler.start_profiling()
fib_gen = fibonacci_generator(n)
# Convert to list to consume the generator for fair comparison
fib_from_gen = list(fib_gen)
gen_stats = profiler.stop_profiling()
print(f"Fibonacci list ({n} items): {format_bytes(list_stats['memory_used'])}")
print(f"Fibonacci from generator: {format_bytes(gen_stats['memory_used'])}")
# Show that generator can be used for infinite sequences
def infinite_counter():
"""Generator for infinite sequence."""
count = 0
while True:
yield count
count += 1
counter = infinite_counter()
print(f"\nInfinite generator first 5 values: {[next(counter) for _ in range(5)]}")
print(f"Generator size: {format_bytes(get_object_size(counter))}")
class DataProcessor:
"""Class demonstrating memory-efficient data processing."""
def __init__(self):
self.processed_count = 0
def process_large_file_inefficient(self, filename: str) -> List[str]:
"""Inefficient: loads entire file into memory."""
try:
with open(filename, 'r') as file:
lines = file.readlines() # Loads all lines into memory
processed = []
for line in lines:
if line.strip(): # Process non-empty lines
processed.append(line.upper().strip())
self.processed_count += 1
return processed
except FileNotFoundError:
return []
def process_large_file_efficient(self, filename: str) -> Generator[str, None, None]:
"""Efficient: processes file line by line."""
try:
with open(filename, 'r') as file:
for line in file: # Generator - one line at a time
if line.strip(): # Process non-empty lines
self.processed_count += 1
yield line.upper().strip()
except FileNotFoundError:
return
# Step 4: Weak references to prevent circular references and memory leaks
# ===============================================================================
# Explanation:
# Weak references allow you to refer to an object without preventing it from
# being garbage collected. This is crucial for breaking circular references
# and preventing memory leaks.
# Previous code from Steps 1-3:
# (All imports, MemoryProfiler, __slots__ classes, and generator functions from above)
class Parent:
"""Parent class that can create circular references."""
def __init__(self, name: str):
self.name = name
self.children = []
self._observers = [] # Regular references
self._weak_observers = [] # Weak references
def add_child(self, child):
"""Add a child - creates potential circular reference."""
self.children.append(child)
child.parent = self # Circular reference!
def add_observer(self, observer):
"""Add observer with strong reference."""
self._observers.append(observer)
def add_weak_observer(self, observer):
"""Add observer with weak reference."""
self._weak_observers.append(weakref.ref(observer))
def notify_observers(self, message: str):
"""Notify all observers."""
# Strong references
for observer in self._observers:
observer.notify(message)
# Weak references - need to check if still alive
for weak_ref in self._weak_observers[:]: # Copy list to avoid modification during iteration
observer = weak_ref() # Get the actual object
if observer is not None:
observer.notify(message)
else:
# Remove dead weak references
self._weak_observers.remove(weak_ref)
class Child:
"""Child class that references parent."""
def __init__(self, name: str):
self.name = name
self.parent = None # Will be set by parent.add_child()
def get_family_info(self) -> str:
if self.parent:
return f"{self.name} is child of {self.parent.name}"
return f"{self.name} has no parent"
class Observer:
"""Observer class for demonstration."""
def __init__(self, name: str):
self.name = name
def notify(self, message: str):
print(f"Observer {self.name} received: {message}")
class WeakParent:
"""Parent class using weak references to prevent circular references."""
def __init__(self, name: str):
self.name = name
self.children = []
def add_child(self, child):
"""Add child with weak reference to parent."""
self.children.append(child)
child.parent_ref = weakref.ref(self) # Weak reference!
def get_info(self) -> str:
return f"Parent {self.name} has {len(self.children)} children"
class WeakChild:
"""Child class using weak reference to parent."""
def __init__(self, name: str):
self.name = name
self.parent_ref = None # Will hold weak reference
def get_parent(self):
"""Get parent object if still alive."""
if self.parent_ref:
return self.parent_ref() # Returns None if parent was garbage collected
return None
def get_family_info(self) -> str:
parent = self.get_parent()
if parent:
return f"{self.name} is child of {parent.name}"
return f"{self.name}'s parent was garbage collected"
def demonstrate_circular_reference_problem():
"""Show how circular references can cause memory issues."""
print("\n=== Circular Reference Problem Demo ===")
profiler = MemoryProfiler()
profiler.start_profiling()
# Create circular references
families = []
for i in range(1000):
parent = Parent(f"Parent{i}")
child1 = Child(f"Child{i}A")
child2 = Child(f"Child{i}B")
parent.add_child(child1)
parent.add_child(child2)
families.append((parent, child1, child2))
stats_with_circular = profiler.stop_profiling()
# Clear references
del families
gc.collect() # Force garbage collection
print(f"Memory used with circular references: {format_bytes(stats_with_circular['memory_used'])}")
def demonstrate_weak_reference_solution():
"""Show how weak references solve circular reference problems."""
print("\n=== Weak Reference Solution Demo ===")
profiler = MemoryProfiler()
profiler.start_profiling()
# Create families with weak references
families = []
for i in range(1000):
parent = WeakParent(f"Parent{i}")
child1 = WeakChild(f"Child{i}A")
child2 = WeakChild(f"Child{i}B")
parent.add_child(child1)
parent.add_child(child2)
families.append((parent, child1, child2))
stats_with_weak = profiler.stop_profiling()
# Test that weak references work
parent, child1, child2 = families[0]
print(f"Before deletion: {child1.get_family_info()}")
# Delete parent
del parent
gc.collect()
print(f"After parent deletion: {child1.get_family_info()}")
print(f"Memory used with weak references: {format_bytes(stats_with_weak['memory_used'])}")
class CacheWithWeakRefs:
"""Cache implementation using weak references."""
def __init__(self):
self._cache = weakref.WeakValueDictionary()
self._access_count = {}
def get(self, key: str, factory_func=None):
"""Get item from cache or create it."""
obj = self._cache.get(key)
if obj is not None:
self._access_count[key] = self._access_count.get(key, 0) + 1
return obj
if factory_func:
obj = factory_func()
self._cache[key] = obj
self._access_count[key] = 1
return obj
return None
def size(self) -> int:
"""Get current cache size."""
return len(self._cache)
def cleanup(self):
"""Clean up access counts for dead objects."""
live_keys = set(self._cache.keys())
dead_keys = set(self._access_count.keys()) - live_keys
for key in dead_keys:
del self._access_count[key]
class ExpensiveObject:
"""Simulate an expensive-to-create object."""
def __init__(self, data: str):
self.data = data
self.creation_time = id(self) # Simulate expensive computation
def __repr__(self):
return f"ExpensiveObject({self.data})"
def demonstrate_weak_cache():
"""Demonstrate cache with weak references."""
print("\n=== Weak Reference Cache Demo ===")
cache = CacheWithWeakRefs()
# Create objects through cache
obj1 = cache.get("key1", lambda: ExpensiveObject("data1"))
obj2 = cache.get("key2", lambda: ExpensiveObject("data2"))
obj3 = cache.get("key1") # Should return same object
print(f"obj1 is obj3: {obj1 is obj3}")
print(f"Cache size: {cache.size()}")
# Delete references
del obj1, obj3
gc.collect()
print(f"Cache size after deletion: {cache.size()}")
# Try to get deleted object
obj4 = cache.get("key1")
print(f"Getting deleted object: {obj4}")
# Create new object with same key
obj5 = cache.get("key1", lambda: ExpensiveObject("new_data1"))
print(f"New object: {obj5}")
# Step 5: Memory-efficient data structures
# ===============================================================================
# Explanation:
# Choosing the right data structure can significantly impact memory usage.
# Some structures are more memory-efficient than others for specific use cases.
# Previous code from Steps 1-4:
# (All imports, MemoryProfiler, __slots__ classes, generators, and weak references from above)
import array
from collections import namedtuple, defaultdict
def compare_data_structure_memory():
"""Compare memory usage of different data structures."""
print("\n=== Data Structure Memory Comparison ===")
size = 100000
# Lists vs Arrays for numeric data
profiler = MemoryProfiler()
# Regular list
profiler.start_profiling()
number_list = [i for i in range(size)]
list_stats = profiler.stop_profiling()
# Array (more memory efficient for numbers)
profiler.start_profiling()
number_array = array.array('i', range(size)) # 'i' for integers
array_stats = profiler.stop_profiling()
print(f"List of {size:,} integers: {format_bytes(list_stats['memory_used'])}")
print(f"Array of {size:,} integers: {format_bytes(array_stats['memory_used'])}")
list_size = get_object_size(number_list)
array_size = get_object_size(number_array)
print(f"List object size: {format_bytes(list_size)}")
print(f"Array object size: {format_bytes(array_size)}")
savings = ((list_size - array_size) / list_size) * 100
print(f"Array saves: {savings:.1f}% memory")
# Named tuples vs regular classes
class RegularCoordinate:
"""Regular class for coordinates."""
def __init__(self, x: float, y: float, z: float):
self.x = x
self.y = y
self.z = z
# Named tuple (more memory efficient)
Coordinate = namedtuple('Coordinate', ['x', 'y', 'z'])
# Coordinate with __slots__
class SlottedCoordinate:
"""Coordinate class with __slots__."""
__slots__ = ['x', 'y', 'z']
def __init__(self, x: float, y: float, z: float):
self.x = x
self.y = y
self.z = z
def compare_coordinate_structures():
"""Compare different ways to store coordinates."""
print("\n=== Coordinate Structure Comparison ===")
size = 50000
profiler = MemoryProfiler()
# Regular class
profiler.start_profiling()
regular_coords = [RegularCoordinate(i, i+1, i+2) for i in range(size)]
regular_stats = profiler.stop_profiling()
# Named tuple
profiler.start_profiling()
named_coords = [Coordinate(i, i+1, i+2) for i in range(size)]
named_stats = profiler.stop_profiling()
# Slotted class
profiler.start_profiling()
slotted_coords = [SlottedCoordinate(i, i+1, i+2) for i in range(size)]
slotted_stats = profiler.stop_profiling()
print(f"Regular class coordinates: {format_bytes(regular_stats['memory_used'])}")
print(f"Named tuple coordinates: {format_bytes(named_stats['memory_used'])}")
print(f"Slotted class coordinates: {format_bytes(slotted_stats['memory_used'])}")
# Single object comparison
regular_coord = RegularCoordinate(1, 2, 3)
named_coord = Coordinate(1, 2, 3)
slotted_coord = SlottedCoordinate(1, 2, 3)
print(f"\nSingle object sizes:")
print(f"Regular: {format_bytes(get_object_size(regular_coord))}")
print(f"Named tuple: {format_bytes(get_object_size(named_coord))}")
print(f"Slotted: {format_bytes(get_object_size(slotted_coord))}")
def demonstrate_efficient_collections():
"""Show memory-efficient collection patterns."""
print("\n=== Efficient Collections Demo ===")
# Using deque for efficient append/pop operations
from collections import deque
# Compare list vs deque for queue operations
profiler = MemoryProfiler()
# List as queue (inefficient)
profiler.start_profiling()
list_queue = []
for i in range(100000):
list_queue.append(i)
if len(list_queue) > 1000:
list_queue.pop(0) # Expensive operation for lists
list_queue_stats = profiler.stop_profiling()
# Deque as queue (efficient)
profiler.start_profiling()
deque_queue = deque(maxlen=1000) # Automatically limits size
for i in range(100000):
deque_queue.append(i) # Automatically removes from left when full
deque_queue_stats = profiler.stop_profiling()
print(f"List as queue: {format_bytes(list_queue_stats['memory_used'])}")
print(f"Deque as queue: {format_bytes(deque_queue_stats['memory_used'])}")
class MemoryEfficientCounter:
"""Memory-efficient counter using __slots__ and defaultdict."""
__slots__ = ['_counts']
def __init__(self):
self._counts = defaultdict(int)
def increment(self, key: str):
self._counts[key] += 1
def get_count(self, key: str) -> int:
return self._counts[key]
def get_size(self) -> int:
return len(self._counts)
class RegularCounter:
"""Regular counter for comparison."""
def __init__(self):
self._counts = {}
def increment(self, key: str):
if key in self._counts:
self._counts[key] += 1
else:
self._counts[key] = 1
def get_count(self, key: str) -> int:
return self._counts.get(key, 0)
def get_size(self) -> int:
return len(self._counts)
def compare_counter_implementations():
"""Compare different counter implementations."""
print("\n=== Counter Implementation Comparison ===")
keys = [f"key_{i % 1000}" for i in range(100000)] # Reuse keys
profiler = MemoryProfiler()
# Regular counter
profiler.start_profiling()
regular_counter = RegularCounter()
for key in keys:
regular_counter.increment(key)
regular_stats = profiler.stop_profiling()
# Efficient counter
profiler.start_profiling()
efficient_counter = MemoryEfficientCounter()
for key in keys:
efficient_counter.increment(key)
efficient_stats = profiler.stop_profiling()
print(f"Regular counter: {format_bytes(regular_stats['memory_used'])}")
print(f"Efficient counter: {format_bytes(efficient_stats['memory_used'])}")
print(f"Both have {regular_counter.get_size()} unique keys")
def demonstrate_string_interning():
"""Show how string interning can save memory."""
print("\n=== String Interning Demo ===")
# Without interning
profiler = MemoryProfiler()
profiler.start_profiling()
strings_without_interning = []
for i in range(10000):
# Create many copies of the same strings
strings_without_interning.extend([
f"common_string_{i % 100}",
f"another_string_{i % 50}",
f"third_string_{i % 25}"
])
without_interning_stats = profiler.stop_profiling()
# With interning
profiler.start_profiling()
# Use a cache to simulate interning
string_cache = {}
strings_with_interning = []
for i in range(10000):
for pattern in [f"common_string_{i % 100}", f"another_string_{i % 50}", f"third_string_{i % 25}"]:
if pattern not in string_cache:
string_cache[pattern] = pattern
strings_with_interning.append(string_cache[pattern])
with_interning_stats = profiler.stop_profiling()
print(f"Without interning: {format_bytes(without_interning_stats['memory_used'])}")
print(f"With interning: {format_bytes(with_interning_stats['memory_used'])}")
print(f"Unique strings cached: {len(string_cache)}")
memory_saved = without_interning_stats['memory_used'] - with_interning_stats['memory_used']
savings_percent = (memory_saved / without_interning_stats['memory_used']) * 100
print(f"Memory saved: {format_bytes(memory_saved)} ({savings_percent:.1f}%)")
# Step 6: Object pooling and reuse
# ===============================================================================
# Explanation:
# Object pooling reuses objects instead of creating new ones, reducing
# memory allocation overhead and garbage collection pressure.
# Previous code from Steps 1-5:
# (All imports, MemoryProfiler, __slots__ classes, generators, weak references, and data structures from above)
from threading import Lock
from queue import Queue
import time
class ExpensiveResource:
"""Simulate an expensive-to-create resource."""
def __init__(self, resource_id: int):
self.resource_id = resource_id
self.created_at = time.time()
self.usage_count = 0
# Simulate expensive initialization
self._data = [i for i in range(1000)] # Some expensive data
def use(self):
"""Use the resource."""
self.usage_count += 1
return f"Using resource {self.resource_id} (used {self.usage_count} times)"
def reset(self):
"""Reset resource for reuse."""
self.usage_count = 0
# Reset any state that needs to be clean for reuse
class ObjectPool:
"""Generic object pool implementation."""
def __init__(self, factory_func, max_size: int = 10):
self._factory_func = factory_func
self._max_size = max_size
self._pool = Queue(maxsize=max_size)
self._created_count = 0
self._lock = Lock()
def acquire(self):
"""Get an object from the pool."""
try:
# Try to get from pool first
obj = self._pool.get_nowait()
return obj
except:
# Pool is empty, create new object
with self._lock:
if self._created_count < self._max_size:
obj = self._factory_func(self._created_count)
self._created_count += 1
return obj
else:
# Wait for an object to be returned
return self._pool.get()
def release(self, obj):
"""Return an object to the pool."""
obj.reset() # Reset object state
try:
self._pool.put_nowait(obj)