Android Memory Optimization: Causes, Tools, Image Strategies, and Online OOM Monitoring with KOOM
This article explains why Android memory optimization is needed, introduces background concepts such as garbage collection and memory leaks, reviews common tools like Memory Profiler, MAT and LeakCanary, details image‑related memory reduction techniques, and presents the open‑source KOOM framework for online OOM detection and analysis.
Preface
Memory problems are widespread but often receive little attention for three reasons: they are hidden, Android uses JVM languages with automatic garbage collection, and they are difficult to locate because the symptom appears far from the root cause.
Memory optimization involves understanding why we need it, learning garbage‑collection basics, mastering common tools, focusing on image‑related memory, and handling OOM (Out‑Of‑Memory) incidents.
1. Why Do We Need Memory Optimization?
1.1 Reduce OOM Rate
Excessive memory allocation without timely release leads to OOM.
1.2 Decrease UI Jank
When GC runs, all threads, including the UI thread, pause, causing frame drops and perceived jank.
1.3 Extend App Lifetime
Android may kill background processes that consume a lot of memory; releasing memory promptly helps keep the app alive longer.
2. Android Memory Optimization Background
2.1 Java Garbage Collection Mechanism
Key concepts include reachability analysis, four reference types (strong, soft, weak, phantom), and various GC algorithms. See the linked article for details.
2.2 What Is a Memory Leak?
A memory leak occurs when an object cannot be reclaimed by GC, e.g., a Handler inner class holding an Activity reference, leading to gradual memory loss and eventual OOM.
Common causes: non‑static inner classes holding outer references, static variables holding a Context, and resources not released promptly.
2.3 What Is Memory Churn?
Frequent creation of temporary objects in a short period creates a saw‑tooth memory pattern, causing repeated GC pauses and UI jank.
To avoid churn: avoid object creation inside loops, avoid allocating objects in custom View onDraw() , and reuse objects via object pools.
2.4 What Is OOM?
OOM (Out‑Of‑Memory) happens when the requested memory exceeds the available heap, causing the app to crash. Various reasons are illustrated in the accompanying diagram.
3. Common Tools and Techniques for Android Memory Optimization
3.1 Memory Profiler
Part of Android Studio, it shows memory curves, detects churn, and can dump Java heap to locate leaks.
3.2 Memory Analyzer Tool (MAT)
Helps locate leaking objects and large memory consumers; more cumbersome than Memory Profiler.
3.3 LeakCanary
Simple library that automatically detects memory leaks at runtime and notifies developers.
3.4 General Optimization Practices
Use largeHeap attribute to increase max heap.
Clear caches when the system signals low‑memory.
Prefer memory‑efficient collections such as SparseArray .
Avoid storing large data in SharedPreferences .
Be cautious with heavy third‑party libraries.
Balance architectural abstraction against memory overhead.
4. Image Memory Optimization
Images often dominate memory usage; optimizing them yields quick gains.
4.1 Conventional Image Optimization Methods
Scale down width/height.
Reduce per‑pixel memory by choosing a suitable bitmap config (e.g., RGB_565 instead of ARGB_8888 ).
Reuse bitmap memory via BitmapFactory.Options.inBitmap .
Load large images partially using BitmapRegionDecoder .
Example of scaling with inSampleSize :
BitmapFactory.Options options = new BitmapFactory.Options();
// set to 4 means width and height become 1/4 of the original
options.inSampleSize = 4;
BitmapFactory.decodeStream(is, null, options);Choosing bitmap config (API 29): ALPHA_8, RGB_565, ARGB_8888, RGBA_F16, HARDWARE, etc., each with different per‑pixel byte costs.
4.2 Image Fallback Strategy
Detect image leaks caused by Activity/Fragment retention in onDetachedFromWindow and release resources accordingly.
4.3 Online Large‑Image Monitoring Solutions
Four approaches are described:
ArtHook : Hook ImageView methods via ART, low intrusion but not suitable for production.
BaseActivity : Scan Views in onDestroy , high intrusion.
ASM Instrumentation : Insert checks at compile time, low runtime impact but higher maintenance cost.
registerActivityLifecycleCallback : Observe Activity lifecycle and check bitmap size on onStop , non‑intrusive and simple.
5. Online OOM Monitoring
5.1 KOOM Overview
KOOM is an open‑source framework (by Kuaishou) that monitors OOM without freezing the app, solves three main problems: GC‑induced jank, hprof dump freeze, and large hprof files.
5.2 KOOM Solves GC Jank
Instead of triggering multiple GCs, KOOM watches memory thresholds (heap size, thread count, file descriptors) and only dumps when thresholds are crossed or OOM occurs.
5.3 KOOM Solves Dump Freeze
Uses copy‑on‑write fork to dump heap in a child process, allowing the main process to continue running.
5.4 KOOM Reduces hprof Size
Trims the dump to keep only necessary structural data, removing actual payload (strings, byte arrays) to protect privacy and reduce size.
5.5 KOOM Improves Parsing Performance
Analyzes only key objects (leaked Activities/Fragments, large bitmaps, textures, arrays) and optimizes the Shark engine, keeping peak memory under 100 MB and cutting parsing time by more than half.
5.6 Using KOOM
KOOM is available on GitHub; integrate it following the guide, and it will automatically capture heap snapshots when thresholds are exceeded, trim and analyze them, and upload a small JSON report containing possible leaks, GC roots, and reference chains.
Conclusion
Memory optimization in Android should start with the most impactful areas: fixing leaks, reducing churn, monitoring large bitmaps, and implementing online OOM detection. Tools such as Memory Profiler, MAT, LeakCanary, and KOOM together provide a systematic approach for both offline and online environments.
References include articles on Android memory optimization, large‑image detection, and OOM monitoring frameworks from Kuaishou, Meituan, and ByteDance.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.