Memory Management Basics
Mobile devices have limited RAM (2-8GB typical). Apps must efficiently manage memory to prevent crashes and ensure smooth performance. Memory issues manifest as app crashes (OOM - Out of Memory), UI lag, battery drain, and poor user experience. Understanding allocation, retention, and deallocation is crucial for mobile developers.
Common Memory Leak Patterns
Memory leaks occur when allocated memory isn't released. Common patterns include: retain cycles (objects holding strong references to each other), closures capturing self strongly, observers not removed, timers not invalidated, and singleton holding references. Even small leaks accumulate over time, eventually crashing the app.
A 1MB leak per screen navigation means your app crashes after visiting 100 screens on a 2GB device.
iOS Memory Management
iOS uses Automatic Reference Counting (ARC). Use weak and unowned references to break retain cycles, capture lists in closures with [weak self], deinit methods to verify deallocation, and Memory Graph Debugger to visualize object relationships. SwiftUI uses @StateObject and @ObservedObject with specific ownership semantics.
Android Memory Management
Android uses garbage collection but still requires careful management. Avoid context leaks (holding Activity references in long-lived objects), use WeakReference for callbacks, clear listeners in onDestroy, use ViewModel for lifecycle-aware data, and implement onTrimMemory to release caches. LeakCanary detects leaks automatically during development.
Profiling Tools
Use Xcode Instruments (Allocations, Leaks) for iOS and Android Profiler (Memory Profiler) for Android. Profile during typical usage scenarios, stress test with rapid navigation, monitor memory over extended sessions, and set memory budgets per feature. Fix leaks immediately - they compound quickly.
Image and Asset Optimization
Images consume significant memory. Downscale images to display size before loading, use appropriate formats (WebP for photos, vector for icons), implement image caching with size limits, lazy load off-screen images, and clear caches on memory warnings. A 4K image can use 50MB of memory uncompressed.
Low Memory Handling
Implement didReceiveMemoryWarning (iOS) and onTrimMemory (Android). Clear caches, release non-essential resources, reduce quality of cached data, and notify user if functionality is limited. Apps that handle low memory gracefully avoid crashes and provide better user experience on budget devices.