This guide provides detailed explanations of Android memory analysis tool output, including SMAPS parsing, HPROF analysis, and comprehensive analysis reports. It helps developers accurately understand analysis results and develop effective memory optimization strategies.
python3 tools/smaps_parser.py -p <pid>
python3 tools/smaps_parser.py -f <smaps_file>python3 tools/hprof_parser.py -f <hprof_file># Analyze dump directory
python3 tools/panorama_analyzer.py -d ./dump
# Analyze individual files
python3 tools/panorama_analyzer.py -m meminfo.txt -g gfxinfo.txt
# JSON output
python3 tools/panorama_analyzer.py -d ./dump --json -o result.json# One-click dump and analyze
python3 analyze.py live --package com.example.app
# Analyze existing data
python3 analyze.py panorama -d ./dump========================================
Android App Memory Analysis Report
Generated: 2025-07-12 22:53:18
Script Version: Universal Android Support
========================================
-
Generated: Analysis report generation time
- Purpose: Track analysis timeline, compare historical data
- Importance: Ensure analysis data currency
-
Script Version: Script version information
- Meaning: "Universal Android Support" indicates support for all Android versions
- Purpose: Ensure analysis functionality compatibility
Memory Overview:
Total Memory Usage: 49.70 MB
Total Swap Memory: 0.00 MB
-
Value Meaning: 49.70 MB
- Calculation Method: Sum of PSS for all memory types
- Importance: π΄ Critical Metric - Application's actual contribution to system memory
- Assessment Standards:
- Lightweight apps: <50MB
- Regular apps: 50-150MB
- Heavy apps: 150-300MB
- Abnormal: >300MB
-
Problem Diagnosis:
# Compare memory usage with similar apps # Check if exceeding reasonable range for app type # Analyze memory growth trends
-
Next Step Tools:
- Exceeds expectations: Deep analysis of memory type distribution
- Continuous growth: Perform memory leak detection
-
Value Meaning: 0.00 MB
- Normal Case: Android typically doesn't use traditional swap, value is 0
- Abnormal Case: Non-zero value indicates high memory pressure, system enabled swap
- Performance Impact: Swap usage significantly affects performance
-
Problem Diagnosis:
# Check system swap configuration cat /proc/swaps # Monitor swap activity vmstat 1
Unknown (Unknown Memory Types) : 0.793 MB
PSS: 0.793 MB
[anon:.bss] : 294 kB
[anon:linker_alloc] : 222 kB
[anon:thread signal stack] : 176 kB
[anon:bionic_alloc_small_objects] : 60 kB
[anon:System property context nodes] : 12 kB
[anon:bionic_alloc_lob] : 8 kB
[anon:arc4random data] : 8 kB
[anon:atexit handlers] : 5 kB
[anon:cfi shadow] : 4 kB
: 4 kB
SwapPSS: 0.000 MB
-
Category Name: "Unknown (Unknown Memory Types)"
- Meaning: Memory regions that couldn't be clearly classified
- Composition: System-level memory, linker, signal handling, etc.
-
Total Size: 0.793 MB
- Calculation: Sum of PSS for all memory regions of this type
- Assessment: Usually 2-5% of total memory, excessive needs analysis
- PSS Value: 0.793 MB
- Meaning: Actual memory usage considering sharing
- Importance: Key data for memory budget calculations
[anon:.bss] : 294 kB
- Meaning: Program's BSS segment (uninitialized global variables)
- Source: Global variable space allocated at compile time
- Characteristics: Zero-initialized data segment
- Problem Diagnosis: Excessive size may indicate too many global variables
- Optimization Suggestion: Reduce global variable usage
[anon:linker_alloc] : 222 kB
- Meaning: Memory allocated by dynamic linker
- Purpose: Dynamic library loading and symbol resolution
- Normal Range: Usually several hundred KB
- Problem: Excessive size may indicate library loading issues
[anon:thread signal stack] : 176 kB
- Meaning: Thread signal handling stack
- Purpose: Temporary stack space during signal handling
- Quantity: Each thread may have one
- Optimization: Check if thread count is reasonable
[anon:bionic_alloc_small_objects] : 60 kB
- Meaning: Bionic C library small object allocator
- Purpose: Efficient allocation of small memory blocks
- Android-specific: Bionic is Android's C library
- Normal: Small usage is normal
Other System Memory:
- System property context nodes (12 kB): System property context
- arc4random data (8 kB): Random number generator data
- atexit handlers (5 kB): Program exit handler functions
- cfi shadow (4 kB): Control Flow Integrity shadow memory
- SwapPSS: 0.000 MB
- Meaning: Swap space usage for this memory type
- Normal: Android typically 0
- Abnormal: Non-zero indicates memory pressure
Dalvik (Dalvik Virtual Machine Runtime Memory) : 3.783 MB
PSS: 3.783 MB
[anon:dalvik-main space (region space)] : 2500 kB
[anon:dalvik-zygote space] : 656 kB
[anon:dalvik-free list large object space] : 327 kB
[anon:dalvik-non moving space] : 300 kB
SwapPSS: 0.000 MB
Overall Assessment:
- Total: 3.783 MB
- Assessment Standards:
- Lightweight apps: <20MB
- Regular apps: 20-80MB
- Heavy apps: 80-200MB
- Abnormal: >200MB
- Assessment Standards:
Main Space Details:
[anon:dalvik-main space (region space)] : 2500 kB
- Meaning: Dalvik/ART main heap space
- Purpose: Java object instance storage
- Importance: π΄ Most Important - Primary Java memory region
- Problem Diagnosis:
- Continuous growth: Java memory leak
- Sudden increase: Large object allocation or caching
- Next Step Tools:
# HPROF analysis python3 hprof_dumper.py -pkg <package> python3 hprof_parser.py -f <hprof_file>
[anon:dalvik-zygote space] : 656 kB
- Meaning: Memory space shared by Zygote process
- Purpose: System classes and preloaded resources
- Characteristics: Shared by multiple processes, saves memory
- Assessment: Relatively stable, slow growth is normal
[anon:dalvik-free list large object space] : 327 kB
- Meaning: Large object space (>12KB objects)
- Purpose: Store bitmaps, large arrays, etc.
- Problem: Large objects easily cause memory fragmentation
- Optimization Suggestions:
- Avoid creating too many large objects
- Release large bitmaps promptly
- Use object pools for reuse
[anon:dalvik-non moving space] : 300 kB
- Meaning: Non-movable object space
- Purpose: Class objects, JNI global references
- Characteristics: Not moved during GC, relatively stable
- Problem: Abnormal growth may indicate JNI reference leaks
Stack (Thread Stack Memory) : 0.976 MB
PSS: 0.976 MB
[anon:stack_and_tls:22379] : 100 kB
[stack] : 60 kB
[anon:stack_and_tls:25810] : 32 kB
[anon:stack_and_tls:24523] : 32 kB
[anon:stack_and_tls:22365] : 32 kB
[anon:stack_and_tls:22241] : 32 kB
[anon:stack_and_tls:21976] : 32 kB
[anon:stack_and_tls:21970] : 32 kB
[anon:stack_and_tls:21963] : 32 kB
[anon:stack_and_tls:21962] : 32 kB
SwapPSS: 0.000 MB
Thread Count Statistics:
- Observation: At least 10 threads (9 worker threads + 1 main thread)
- Calculation Method: Each
stack_and_tls:xxxxxrepresents a thread - Assessment Standards:
- Normal: 5-20 threads
- Many: 20-50 threads
- Too many: >50 threads
Main Thread Stack: [stack] : 60 kB
- Meaning: Main thread stack space
- Normal Size: Usually 8MB virtual space, actual usage tens of KB
- Problem: Excessive size may indicate deep recursion
Worker Thread Stacks: [anon:stack_and_tls:22379] : 100 kB
- Meaning: Worker thread stack + Thread Local Storage
- Composition: Function call stack + TLS data
- Size Analysis:
- 100 kB: May have deep calls or large local variables
- 32 kB: Normal thread stack usage
Optimization Suggestions:
# Check thread count
adb shell "ls /proc/<pid>/task | wc -l"
# Analyze thread purposes
adb shell "cat /proc/<pid>/task/*/comm"
# Monitor thread stack usage
watch -n 5 "cat /proc/<pid>/smaps | grep stack | wc -l"Gfx dev (Graphics Device Memory) : 5.884 MB
PSS: 5.884 MB
/dev/kgsl-3d0 : 5884 kB
SwapPSS: 0.000 MB
Total Assessment:
- 5.884 MB: Graphics memory usage
- Assessment Standards:
- Lightweight apps: <10MB
- Regular apps: 10-50MB
- Graphics-intensive: 50-200MB
- Game apps: May be higher
Device Details: /dev/kgsl-3d0 : 5884 kB
- Meaning: Qualcomm GPU graphics memory device
- Purpose:
- OpenGL textures and buffers
- Render targets and framebuffers
- GPU compute memory
- Characteristics:
- Cannot be swapped to storage
- Directly uses video memory
- Affects graphics performance
Problem Diagnosis:
- Excessive size causes:
- Large uncompressed textures
- Too many render buffers
- Resources not released promptly
Next Step Tools:
# GPU memory details (if supported)
adb shell "cat /d/kgsl/proc/<pid>/mem"
# Graphics performance analysis
adb shell "dumpsys gfxinfo <package> framestats"
# GPU debugging tools
# Mali Graphics Debugger, RenderDoc.so mmap (Dynamic Library Mapped Memory) : 2.608 MB
PSS: 2.608 MB
/vendor/lib64/libllvm-glnext.so : 859 kB
/system/lib64/libhwui.so : 804 kB
/vendor/lib64/egl/libGLESv2_adreno.so : 235 kB
/system/lib64/libgui.so : 75 kB
/system/lib64/libsqlite.so : 70 kB
/system/lib64/libft2.so : 57 kB
/system/lib64/libandroid_runtime.so : 54 kB
/system/lib64/libharfbuzz_ng.so : 48 kB
/system/lib64/libmediandk.so : 36 kB
/system/lib64/libminikin.so : 29 kB
SwapPSS: 0.000 MB
Overall Assessment:
- 2.608 MB: Shared library memory contribution
- Characteristics: PSS values usually much smaller than actual library size (due to sharing)
- Efficiency: Demonstrates advantages of shared memory
Main Library Analysis:
Graphics-related Libraries:
- libllvm-glnext.so (859 kB): LLVM GPU compiler
- libGLESv2_adreno.so (235 kB): Adreno GPU OpenGL ES driver
- libhwui.so (804 kB): Android hardware UI rendering library
System Core Libraries:
- libgui.so (75 kB): Graphical User Interface library
- libandroid_runtime.so (54 kB): Android runtime library
- libsqlite.so (70 kB): SQLite database library
Font and Text:
- libft2.so (57 kB): FreeType font rendering
- libharfbuzz_ng.so (48 kB): Text layout engine
- libminikin.so (29 kB): Android text layout
Optimization Analysis:
# Calculate sharing efficiency
# If single library actual size is 5MB, but PSS only 500KB
# Indicates library shared by 10 processes: 5MB / 10 = 500KB
# Check library dependencies
adb shell "cat /proc/<pid>/maps | grep '\.so' | wc -l"
# Analyze library loading timing
# Consider lazy loading of infrequently used libraries.apk mmap (APK File Mapped Memory) : 3.048 MB
PSS: 3.048 MB
/system_ext/priv-app/Launcher3QuickStep/Launcher3QuickStep.apk : 2480 kB
/system/framework/framework-res.apk : 508 kB
/product/app/QuickSearchBox/QuickSearchBox.apk : 60 kB
SwapPSS: 0.000 MB
Main Application APK: Launcher3QuickStep.apk : 2480 kB
- Meaning: Main application APK memory mapping
- Contains: DEX code, resource files, Native libraries
- Optimization: Relatively low PSS indicates some sharing
System Framework: framework-res.apk : 508 kB
- Meaning: Android system resource package
- Sharing: Shared by all applications
- Efficiency: High sharing reduces per-application cost
Problem Analysis:
- Excessive APK memory:
- Check APK file size
- Analyze resource usage efficiency
- Consider resource compression and on-demand loading
.art mmap (ART Runtime File Mapped Memory) : 2.727 MB
PSS: 2.727 MB
[anon:dalvik-/system/framework/boot-framework.art] : 1537 kB
[anon:dalvik-/apex/com.android.art/javalib/boot.art] : 369 kB
[anon:dalvik-/data/dalvik-cache/arm64/app.art] : 344 kB
[anon:dalvik-/system/framework/boot-core-icu4j.art] : 230 kB
[anon:dalvik-/apex/com.android.art/javalib/boot-core-libart.art] : 97 kB
[anon:dalvik-/system/framework/boot-telephony-common.art] : 58 kB
[anon:dalvik-/system/framework/boot-voip-common.art] : 30 kB
/system/framework/arm64/boot-framework.art : 16 kB
[anon:dalvik-/apex/com.android.art/javalib/boot-bouncycastle.art] : 10 kB
[anon:dalvik-/apex/com.android.art/javalib/boot-okhttp.art] : 8 kB
SwapPSS: 0.000 MB
System Framework ART: boot-framework.art : 1537 kB
- Meaning: AOT compiled code for Android framework
- Purpose: Improve system startup and runtime performance
- Sharing: System-level sharing, benefits multiple applications
Application-specific ART: app.art : 344 kB
- Meaning: AOT compiled version of application code
- Purpose: Improve application startup speed and execution efficiency
- Generation: Compiled during app installation or system idle time
Performance Impact:
- Memory for Performance: ART files use memory but improve execution efficiency
- Startup Optimization: Pre-compiled code reduces startup time
scudo heap (Scudo Security Memory Allocator) : 24.482 MB
PSS: 24.482 MB
[anon:scudo:primary] : 16491 kB
[anon:scudo:secondary] : 7991 kB
SwapPSS: 0.000 MB
Overall Assessment:
- 24.482 MB: Main portion of Native memory usage
- Importance: π΄ Critical - Primary indicator of Native memory leaks
- Android Version: Default on Android 11+
Main Pool Details: [anon:scudo:primary] : 16491 kB
- Meaning: Primary memory pool for common-sized allocations
- Characteristics:
- Efficient small to medium-sized memory allocation
- Provides security protection mechanisms
- Detects memory errors
[anon:scudo:secondary] : 7991 kB
- Meaning: Secondary memory pool for large memory allocations
- Purpose: Memory blocks larger than primary pool allocation granularity
- Characteristics: Handles irregular-sized allocations
Problem Diagnosis:
-
Continuous growth: Native memory leak
# Detailed Native memory analysis adb shell "dumpsys meminfo <package> -d" # Check Native memory allocation # Use AddressSanitizer or malloc hooks
-
Abnormally large values: Check JNI code, third-party libraries
-
Allocation patterns: Analyze primary vs secondary ratio
Starting HPROF file parsing: com.tencent.mm_8234_20250112_143022.hprof
HPROF version: JAVA PROFILE 1.0.3
Identifier size: 4 bytes
Timestamp: 2025-01-12 14:30:22
- HPROF version: Standard Java heap dump format version
- Identifier size: Bytes for object references (32-bit=4 bytes, 64-bit=8 bytes)
- Timestamp: Exact time of heap dump
=== Memory Analysis Complete ===
Total instances: 2,456,789
Instance total size: 89.34 MB
Total arrays: 345,678
Array total size: 23.45 MB
Total memory usage: 112.79 MB
Total instances: 2,456,789
- Meaning: Total number of all object instances in Java heap
- Assessment Standards:
- Lightweight apps: <1 million
- Regular apps: 1-5 million
- Heavy apps: 5-20 million
- Abnormal: >20 million
- Problem Diagnosis: Too many instances may indicate:
- Overly frequent object creation
- Lack of object reuse mechanisms
- Object accumulation due to memory leaks
Instance total size: 89.34 MB
- Meaning: Total memory occupied by all regular objects
- Calculation: Sum of object memory excluding arrays
- Proportion: Usually 60-80% of Java heap
Total arrays: 345,678
- Meaning: Number of all array objects in heap
- Includes: Primitive type arrays and object arrays
- Focus: Memory usage of large arrays
Array total size: 23.45 MB
- Meaning: Memory occupied by all array objects
- Proportion: Usually 20-40% of Java heap
- Problem: Excessive proportion may indicate large array leaks
Total memory usage: 112.79 MB
- Calculation: Instance total size + Array total size
- Comparison: Should be close to Dalvik memory in SMAPS
- Difference: HPROF only counts Java objects, SMAPS includes JVM overhead
=== TOP 20 Memory Consuming Classes (minimum 0.1MB) ===
Class Name Instances Total Size(MB) Avg Size(KB)
--------------------------------------------------------------------------------------
java.lang.String 234,567 15.67 0.07
android.graphics.Bitmap 1,234 12.34 10.24
com.tencent.mm.ui.ChatActivity 45 8.91 203.56
byte[] 89,012 7.23 0.08
java.util.HashMap$Node 123,456 6.78 0.06
android.view.View 45,678 5.43 0.12
com.tencent.mm.model.Message 23,456 4.32 0.19
java.lang.String - 15.67 MB
- Instances: 234,567 (highest count)
- Average size: 0.07 KB (very small)
- Analysis:
- Many string objects but individually very small
- Possible string duplication issues
- Consider string constant pool optimization
- Optimization Suggestions:
// Use StringBuilder to avoid frequent string concatenation StringBuilder sb = new StringBuilder(); // Reuse string constants private static final String CONSTANT = "constant string"; // Use intern() to reduce duplicate strings String optimized = someString.intern();
android.graphics.Bitmap - 12.34 MB
- Instances: 1,234 (relatively few)
- Average size: 10.24 KB (larger)
- Analysis:
- Bitmaps are key memory users
- Individual bitmaps use more memory
- Need to focus on image usage optimization
- Problem Diagnosis:
# Calculate if bitmap count is reasonable # 1,234 bitmaps is quite a lot, check for leaks # Average 10KB isn't too large, but total needs control
- Optimization Suggestions:
// Recycle bitmaps promptly if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); } // Use appropriate image format and size BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2; // Scale down options.inPreferredConfig = Bitmap.Config.RGB_565; // Reduce memory
com.tencent.mm.ui.ChatActivity - 8.91 MB
- Instances: 45 (abnormally many)
- Average size: 203.56 KB (very large)
- Problem Analysis: π¨ Serious Issue
- Too many Activity instances (should only be 1-2)
- Individual Activity too large
- Clear Activity memory leak
- Leak Causes:
- Static references holding Activity
- Handler not properly cleaned
- Listeners not unregistered
- Anonymous inner classes holding outer references
- Next Step Tools:
# Use LeakCanary for automatic detection # Use MAT (Memory Analyzer Tool) to analyze reference chains # Check Activity reference paths
byte[] - 7.23 MB
- Analysis: Byte arrays, commonly used for:
- Image data storage
- Network data caching
- File read/write buffers
- Optimization: Check for unnecessary byte array caching
java.util.HashMap$Node - 6.78 MB
- Analysis: HashMap internal nodes
- Instances: 123,456 (many)
- Problem: Possibly too many HashMaps or single HashMap too large
- Optimization: Consider using SparseArray or other lightweight collections
=== TOP 10 Primitive Array Memory Usage ===
Array Type Array Count Total Size(MB) Avg Size(KB)
----------------------------------------------------------
byte[] 89,012 7.23 0.08
int[] 12,345 3.45 0.29
char[] 56,789 2.78 0.05
long[] 3,456 1.23 0.37
byte[] Arrays:
- Count: 89,012 (most)
- Total size: 7.23 MB
- Average size: 0.08 KB (very small)
- Possible uses:
- Image decoding buffers
- Network data packets
- Byte representation of strings
- Optimization: Consider object pools for reusing small byte arrays
int[] Arrays:
- Average size: 0.29 KB (relatively large)
- Possible uses: Pixel data, coordinate arrays, index arrays
char[] Arrays:
- String-related: char[] is internal storage for String
- Large count: Corresponds to String count
long[] Arrays:
- Largest average: 0.37 KB
- Possible uses: Timestamp arrays, ID arrays
=== String Memory Statistics ===
String instances: 234,567
String total size: 15.67 MB
Average string size: 70.12 bytes
String density: 15.67MB / 112.79MB = 13.9%
- Assessment: Moderate string proportion
- Optimization potential: Still room for optimization
Average size: 70.12 bytes
- Analysis: Medium-length strings
- Comparison:
- <50 bytes: Short strings, consider constant pool
- 50-200 bytes: Medium length, normal
-
200 bytes: Long strings, check if necessary
Optimization Strategies:
// 1. String constant pool
private static final String[] COMMON_STRINGS = {
"common string 1", "common string 2"
};
// 2. StringBuilder reuse
private final StringBuilder mStringBuilder = new StringBuilder();
// 3. String caching
private final LruCache<String, String> mStringCache =
new LruCache<>(100);==========================================================
Android Application Memory Comprehensive Analysis Report
==========================================================
π Memory Usage Summary:
------------------------------
Total Memory Usage: 245.67 MB
Java Heap Memory: 89.34 MB
Native Heap Memory: 34.21 MB
Dalvik Runtime: 12.45 MB
Native Code: 23.78 MB
Java Heap Percentage: 36.4%
Total Memory Usage: 245.67 MB
- Source: Sum of PSS from SMAPS analysis
- Includes: Java heap + Native heap + System overhead
- Assessment: Includes complete process memory compared to pure HPROF
Java Heap Percentage: 36.4%
- Calculation: 89.34 MB / 245.67 MB
- Assessment Standards:
- Balanced apps: 30-50%
- Java-heavy apps: 50-70%
- Native-heavy apps: 20-40%
- Analysis: This app has balanced Java and Native memory usage
π Memory Category Usage (>1MB):
------------------------------
Dalvik (Dalvik Virtual Machine Runtime Memory): 89.23 MB
graphics (Graphics Related Memory): 45.67 MB
Native (Native C/C++ Code Memory): 34.21 MB
.so mmap (Dynamic Library Mapped Memory): 23.78 MB
native heap (Native Heap Memory): 12.45 MB
Dalvik Memory: 89.23 MB (36.3%)
- Assessment: Reasonable proportion
- Focus: Whether there are continuous growth trends
Graphics Memory: 45.67 MB (18.6%)
- Assessment: Graphics memory proportion is high
- Problem: Possible UI overdraw or texture leaks
- Optimization: Check bitmap usage and GPU resource management
Total Native Memory: 34.21 + 12.45 = 46.66 MB (19.0%)
- Assessment: Moderate Native memory usage
- Distribution: Distributed across heap memory and code segments
π‘ Optimization Recommendations:
------------------------------
β οΈ [Java Heap Memory] Java heap memory usage is large (89.3MB), recommend checking for memory leaks
βΉοΈ [String Optimization] Strings occupy 15.7MB, recommend optimizing string usage, consider using StringBuilder or string constant pool
βΉοΈ [Graphics Memory] Graphics memory usage is high (45.7MB), check bitmap cache and GPU memory usage
βΉοΈ [Native Memory] Native heap memory usage is high (34.2MB), check JNI code and third-party libraries
π΄ High Priority: Java Heap Memory Check
# 1. Perform memory leak detection
python3 hprof_dumper.py -pkg <package> -o before/
# Perform operations
python3 hprof_dumper.py -pkg <package> -o after/
# Compare analysis
# 2. Use automatic detection tools
# Integrate LeakCanary
implementation 'com.squareup.leakcanary:leakcanary-android:2.12'
# 3. MAT tool analysis
# Download Eclipse Memory Analyzer Tool
# Import HPROF file to analyze reference chainsπ‘ Medium Priority: String Optimization
// 1. String constant pool usage
private static final String CACHED_STRING = "common string";
// 2. StringBuilder reuse
private final StringBuilder mBuilder = new StringBuilder(256);
// 3. String caching
private final Map<String, String> mStringCache = new HashMap<>();π’ Low Priority: Graphics Memory Optimization
// 1. Bitmap recycling
if (bitmap != null && !bitmap.isRecycled()) {
bitmap.recycle();
bitmap = null;
}
// 2. Image loading optimization
Glide.with(context)
.load(url)
.override(targetWidth, targetHeight)
.format(DecodeFormat.PREFER_RGB_565)
.into(imageView);
// 3. LRU cache
private final LruCache<String, Bitmap> mBitmapCache =
new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount();
}
};com.example.MainActivity: 5 instances, 12.3 MB
Characteristics: Activity instances > 2 Causes: Static references, Handlers, listeners Solutions:
// 1. Avoid static references to Activity
// Wrong
private static Context sContext;
// Correct
private static WeakReference<Context> sContextRef;
// 2. Proper Handler usage
private static class MyHandler extends Handler {
private final WeakReference<Activity> mActivityRef;
MyHandler(Activity activity) {
mActivityRef = new WeakReference<>(activity);
}
}
// 3. Unregister listeners
@Override
protected void onDestroy() {
eventBus.unregister(this);
super.onDestroy();
}java.util.ArrayList: 50,000 instances, 25.6 MB
Characteristics: Abnormally many collection instances Causes: Collections not cleaned, unlimited cache growth Solutions:
// 1. Use WeakHashMap
Map<Key, Value> cache = new WeakHashMap<>();
// 2. LRU cache
LruCache<String, Object> cache = new LruCache<>(maxSize);
// 3. Regular cleanup
if (cache.size() > MAX_SIZE) {
cache.clear();
}android.graphics.Bitmap: 2 instances, 48.5 MB average: 24.25 MB
Characteristics: Individual objects abnormally large Solutions:
// 1. Image compression
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inPreferredConfig = Bitmap.Config.RGB_565;
// 2. Tile loading for large images
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(inputStream, false);
Bitmap region = decoder.decodeRegion(rect, options);byte[]: 10 instances, 32.1 MB average: 3.21 MB
Solutions:
// 1. Stream processing
try (InputStream is = new FileInputStream(file);
OutputStream os = new FileOutputStream(output)) {
byte[] buffer = new byte[8192]; // Small buffer
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
// 2. Object pool reuse
public class ByteArrayPool {
private final Queue<byte[]> pool = new ConcurrentLinkedQueue<>();
public byte[] acquire(int size) {
byte[] array = pool.poll();
if (array == null || array.length < size) {
array = new byte[size];
}
return array;
}
public void release(byte[] array) {
pool.offer(array);
}
}# Many small objects
java.lang.Object: 1,000,000 instances, average: 24 bytes
# Discontinuous memory usage
Virtual: 512 MB, RSS: 128 MB (25% utilization)// 1. Object pool
public class ObjectPool<T> {
private final Queue<T> pool = new ArrayDeque<>();
private final Factory<T> factory;
public T acquire() {
T item = pool.poll();
return item != null ? item : factory.create();
}
public void release(T item) {
reset(item);
pool.offer(item);
}
}
// 2. Memory pre-allocation
List<Object> preAllocated = new ArrayList<>(expectedSize);
// 3. Reduce temporary objects
// Wrong: Frequent object creation
for (int i = 0; i < 1000; i++) {
String temp = "prefix" + i + "suffix";
}
// Correct: Reuse StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.setLength(0);
sb.append("prefix").append(i).append("suffix");
String result = sb.toString();
}- Application Level Analysis: dumpsys meminfo Interpretation Guide
- System Level Analysis: /proc/meminfo Interpretation Guide
- Process Level Overview: showmap Interpretation Guide
- Detailed Mapping Analysis: smaps Interpretation Guide
- Eclipse MAT: Memory Analyzer Tool
- VisualVM: Java Performance Analysis
- YourKit: Commercial Java profiler
- AddressSanitizer: ASan Memory Error Detection
- Valgrind: Linux Memory Analysis
- Heaptrack: Heap Memory Tracking
- LeakCanary: Automatic Memory Leak Detection
- Android Studio Profiler: Official Performance Analysis
- Perfetto: Modern Tracing Tool
- analyze.py: Entry script, supports live dump and panorama analysis
- panorama_analyzer.py: Core panorama analysis
- hprof_parser.py: HPROF file parsing
- smaps_parser.py: SMAPS file parsing
- meminfo_parser.py: dumpsys meminfo parsing
- gfxinfo_parser.py: dumpsys gfxinfo parsing
- zram_parser.py: zRAM/Swap analysis
- diff_analyzer.py: Diff analysis
- Android Memory Management: Official Documentation
- Memory Optimization Guide: Best Practices
- Bitmap Optimization: Image Processing Guide
This guide focuses on how to interpret analysis outputs.
For standardized team execution, report templates, and Android 16-compatible teaching workflow, use:
Recommended usage:
- Use this document for output interpretation and diagnosis logic.
- Use
teaching_playbook.mdfor workshop flow, monitoring script baseline, and review checklists. - Keep baseline and verification runs on the same capture strategy to avoid data drift.