Leveraging Android Studio’s Memory Profiler to tackle Memory Leaks
and other tools to tackle Memory Leaks
Introduction
In the previous three articles we learned about memory leaks, WeakReference and the garbage collector. Today, we are going to learn about tools that can help us identify memory leaks.
Android Studio’s memory profiler is a powerful tool for detecting and analyzing memory issues.
Memory Profiler: chart analysis
The memory profiler hook to the app and capture the memory heap. You can visually spot a big memory leak (like when Bitmaps are leaked). You will see the memory gradually increasing an no release. While the garbage collector is triggered (each bin icon at the bottom), the memory continues to increase.
While this indicate there is a memory leak, it doesn’t say where it comes from.
Memory Profiler: heap dump
The profiler allows you to capture the heap, it will analyses the memory heap to identify objects that are consuming excessive memory. Look for unexpected instances of large objects or objects that should have been garbage collected.
Android Studio is able to find leaks from the heap dump. You can then inspect and find what objects are leaking and where they are referenced.
Memory Profiler: Allocation tracker
Another powerful tool is the allocation tracker. It monitors memory allocation over time to identify potential memory leaks. You can see the memory growing. When launching the memory profiler, tick “Select record Java / Kotlin allocations”.
On this short video you can see that the byte[]
's memory is increasing, it is a sign of a memory leak.
Third-party tool: LeakCanary
LeakCanary is a powerful tool that significantly simplifies the process of detecting memory leaks. By automatically monitoring your app for leaks and providing clear, actionable reports, it is faster compared to manual memory profiling.
Leak Canary is easy to install with just one line in build.gradle.kts
:
Note: Leak Canary will only run for debug variants (do not use it in production).
dependencies {
// debugImplementation because LeakCanary should only run in debug builds.
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.14'
}
Leak Canary cannot detect all leaks, but excel at finding the Android leaks such as:
Activity
Fragment
View
ViewModel
Context
Conclusion
By understanding the causes of memory leaks and effectively using tools like the memory profiler, you can significantly improve the performance and stability of your Android app. Tools like Leak Canary are easy to set up and provide great insight on memory leaks.
If you read this far, please consider clapping 👏🏼 to support the author, thank you 🙏🏼
This article is sponsored by Android Developer News, app is available on the playstore.