pythonintermediate
Optimize Memory with __slots__
Reduce memory usage for classes with many instances using __slots__.
pythonPress ⌘/Ctrl + Shift + C to copy
import sys
# Without __slots__: each instance has a __dict__
class PointRegular:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
# With __slots__: fixed attribute set, no __dict__
class PointSlotted:
__slots__ = ('x', 'y', 'z')
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
# Compare memory usage
regular = PointRegular(1.0, 2.0, 3.0)
slotted = PointSlotted(1.0, 2.0, 3.0)
print(f"Regular: {sys.getsizeof(regular) + sys.getsizeof(regular.__dict__)} bytes")
print(f"Slotted: {sys.getsizeof(slotted)} bytes")
# Slotted prevents dynamic attributes
try:
slotted.w = 4.0 # AttributeError!
except AttributeError as e:
print(f"Cannot add: {e}")
# Great for millions of instances
points = [PointSlotted(i, i, i) for i in range(1_000_000)]Use Cases
- Memory-constrained applications
- Game entities
- Large datasets
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Python Itertools Recipes
Practical itertools patterns for batching, flattening, grouping, and combining iterables.
Best for: Efficient batch processing of large datasets
#python#itertools
typescriptintermediate
In-Memory Response Cache
Simple TTL-based in-memory cache middleware for GET endpoints that serves cached responses.
Best for: Caching expensive queries
#cache#performance
typescriptbeginner
Next.js Image Optimization Patterns
Use next/image with responsive sizes, blur placeholders, and priority loading for optimal Core Web Vitals.
Best for: Hero images
#images#optimization
typescriptbeginner
Next.js Image Optimization Patterns
Advanced next/image usage with responsive sizes, blur placeholders, and custom loaders.
Best for: Optimizing Core Web Vitals with proper image loading
#nextjs#image