SlideShare a Scribd company logo
@snnkzk
Unblocking The Main Thread:
Solving ANRs and Frozen Frames
Sinan Kozak
Staff Android Developer
Google Developer Expert
@snnkzk
2
Sinan Kozak
12 years Android experience
Google Developer Expert
Staff Android Developer
@snnkzk
I wrote a chapter about performance in 2014
book with GDG community Ankara, Turkey.
@snnkzk
3
We deliver
food over
70 countries
with a single rider application
@snnkzk
4
Production is wild,
really wild for Android
10s of thousands of different devices
@snnkzk
5
5
@snnkzk
6
Different stages of
Jank
What to measure?
@snnkzk
7
Rendering a frame
between 16ms and 700ms
Scroll
Animations
Frame render
Slow Rendering
Rendering a frame
between 700ms and 5s
App startup
Navigation
Frozen Frame
Blocking main thread
over 5 seconds
Not being able to
handle user inputs
Application Not Responding
Different stages of Jank
@snnkzk
8
Apps have limited
resources
Focus on things we can control
@snnkzk
9
What bad rendering looks like
@snnkzk
10
What acceptable render looks like
@snnkzk
11
Can slow runtime cause app crashes?
YES
● User will continue to click the screen. New events without being
able to handle to current event will cause unexpected app states.
● Foreground services crashes when their start is delayed
@snnkzk
12
Is there a magic
solution?
Maybe…
@snnkzk
13
Reuse thread pool
Reducing allocation
Fix memory leaks
Release Memory Pressure
R8/Proguard optimization
Fast dependency Injection
WebP and vector images
Use reportFullyDrawn
Baseline profile
Render First Frame
Execute in background
Reduce recomposition
Use correct Compose APIs
Measure and optimize
Drain Main Thread
Different categories of solutions
@snnkzk
14
Quick wins
01 Execute in background
RxJava, Coroutine and other thread solutions
02 Thread pool reuse
Utilize thread pools
03 R8/Proguard optimization
Auto apply proven optimizations
04 Reducing allocation
Only store necessary data in memory
05 No memory leak
Fix all leaks
06 Dependency Injection
Time consuming injection should be in background
07 WebP and vector images
Simpler the image faster to draw
08 Less recomposition
Avoid recurring recomposition
09 Correct Compose API
Use lambda based api for fast changing values
10 reportFullyDrawn
Talk to OS about what needs to prioritize
11 Baseline profile
Make sure OS optimize app startup
12 Measure and optimize
We can have optimized apps
@snnkzk
15
15
Reducing
allocation
Garbage collector pauses
runtime to clean up
Spare memory for all features
Photo by Andreas Gücklhorn on Unsplash
@snnkzk
16
Reducing allocation
@snnkzk
17
In your heap dump, look for memory leaks caused by any of the following:
● Long-lived references to Activity, Context, View, Drawable, and other objects
that might hold a reference to the Activity or Context container.
● Non-static inner classes, such as a Runnable, that can hold an Activity instance.
● Caches that hold objects longer than necessary.
Memory leak
In your heap dump, look for memory leaks caused by any of the
following:
● Long-lived references to Activity, Context, View, Drawable, and
other objects that might hold a reference to the Activity or
Context container.
● Non-static inner classes, such as a Runnable, that can hold an
Activity instance.
● Caches that hold objects longer than necessary.
@snnkzk
18
Running with memory leaks
@snnkzk
19
Memory leak
Detection:
● Leak Canary
● Android Studio
● Strict Mode
● Third party memory analyzer
Leak Canary Plumber fixes known common issues.
https://github.com/square/leakcanary/tree/main/plumber
@snnkzk
20
Share Thread Pools
A single thread can use 1-3 MB memory
@snnkzk
21
Share Thread Pools
Most of features have their own thread pool
● RxJava
● Coroutine
● OkHttp
● Image loader
● AsyncTask
● AndroidX arch components
● RecyclerView + DiffUtil
● WorkManager
● … many more
And they have APIs to change thread pool
@snnkzk
22
Share Thread Pools
We shared Coroutine Dispatchers with
● RxJava
● OkHttp
● Coil
● WorkManager
Thread count reduced 180+ to 130~ after refresh action
“asOkHttpExecutorService” is a custom implementation that only handle execute function
@snnkzk
23
Runtime optimization
Code we write is not same as core runs on device
@snnkzk
24
R8 and proguard are mainly obfuscation tools, but…
They also shrink and optimize codes.
In order to optimize your app even further, R8 inspects your code at a deeper level to
remove more unused code or, where possible, rewrite your code to make it less
verbose. The following are a few examples of such optimizations:
● If your code never takes the else {} branch for a given if/else statement, R8
might remove the code for the else {} branch.
● If your code calls a method in only a few places, R8 might remove the method
and inline it at the few call sites.
Prefer "proguard-android-optimize.txt" over default
Improve app performance by up to 30%
R8/Proguard optimization
@snnkzk
25
More resources optimizations
High level documentation
https://developer.android.com/build/shrink-code
https://www.guardsquare.com/manual/configuration/optimizations
Detailed posts
https://jakewharton.com/blog/
@snnkzk
26
Use multi thread
solutions
● IO operations
● Data parsing
● Encryption
● Any time consuming operation
Move work to the background
Photo by Campbell on Unsplash
@snnkzk
27
Execute in background with Coroutine
https://kotlinlang.org/docs/coroutines-overview.html
https://developer.android.com/kotlin/coroutines#use-coroutines-for-main-safety
@snnkzk
28
Compose recomposition
optimizations
Does count matter?
@snnkzk
29
Recomposition
Recompose count shouldn’t affect correctness.
The compose runtime might end up recomposing a lot more than
you’d expect.
Just looking at the code does not reveal reasons.
Functions can be inline
Classes can be mutable
@snnkzk
30
https://dev.to/zachklipp/scoped-recomposition-jetpack-compose-what-happens-when-state-changes-l78
Donut hole skipping
Compose API design enforces
better performance with
lambda and scoping
@snnkzk
31
Donut hole skipping
● Lambdas are special in Compose
● The runtime keeps track of values used in lambdas
● Lambdas get reevaluated if values change
● Composable can be skipped if they are not affected by change
@snnkzk
32
Compose API design
@snnkzk
33
Rendering first pixel
Costly operations during start up
@snnkzk
34
WebP
WebP is an image file format from Google that provides lossy compression
(like JPEG) as well as transparency (like PNG) but can provide better
compression than either JPEG or PNG
Average %26 less space
More efficient
Android Studio can convert images
https://developer.android.com/studio/write/convert-webp
Resource optimizations
@snnkzk
35
Resource optimizations
Vector Drawables
is a vector graphic defined in an XML file as a
set of points, lines, and curves along with its
associated color information.
Scalable
svg can be converted to Vector drawables
Simpler is better
The initial loading of a vector drawable can cost
more CPU cycles than the corresponding raster
image.
Size save should be justified with performance
Use Avocado tool to simplify complex vectors
https://github.com/alexjlockwood/avocado
@snnkzk
36
Resource optimizations
@snnkzk
37
Dependency Injection
DI slowness effects first frame rendering
@snnkzk
38
Dependency Injection P50
P90
One of the our major
improvements is creating OkHttp
and Encrypted SharedPreference
in the background thread.
@snnkzk
39
Dependency Injection
Delay creation of expensive instances
Create in background thread
If you use Dagger, get instances from Provider or dagger.Lazy
@snnkzk
40
Play Store helps you
Use reportFullyDrawn for better cloud profiles
@snnkzk
41
Baseline Profiles
● Helps app startup after new install or update
● Android run ahead of time compile to prepare app startup
● We can modify and create aggregated profiles
● Libraries can have their own baseline profiles
● Compose benefit from baseline profiles
https://developer.android.com/topic/performance/baselineprofiles/create-baselineprofile
@snnkzk
42
Show me real example
Dependency injection issue
Inefficient vector drawable usage
@snnkzk
43
Effect of Vector Drawable
@snnkzk
44
Creation of Vector Images can be consuming
@snnkzk
45
Effect of Vector Drawable
@snnkzk
46
46
Talk to
designers for
simpler svgs
You can use webp images or
image loading libraries
@snnkzk
47
Random ANR points during app start up
ANR stacktrace is delayed
Android 14 has improved ANR capturing
Filter ANR for Android 14 to get better picture
ANR report only contain last executed things
There could be other slowness on main thread
@snnkzk
48
Measure as much as you can
● Profile a variant close to release
● Measure high level first
● Add more granular metrics
● Use benchmark tests
● Profile before and after changes
● Collect data from production
@snnkzk
49
49
How to
measure?
Real data vs profiling
@snnkzk
50
How to measure?
Data from profiling
● perfetto.dev
● Systrace
● CPU and memory allocation
● Layout inspector and debugger
Data from users
● Firebase Performance Monitoring or similar solutions
● JankStat library
● Memory leaks
● Strict mode
@snnkzk
51
@snnkzk
52
52
Collect
StrictMode
violations
Easiest way to collect data
@snnkzk
53
Collect StrictMode violations
@snnkzk
54
Collect StrictMode violations
@snnkzk
55
Visible performance is
one side of the coin
App needs to be performant in all operations.
@snnkzk
56
10 years retro of
performance suggestions
Comments are welcome in QA
@snnkzk
57
@snnkzk
58
10 years retro of performance suggestions
View hierarchy - ViewStub > Composables with if check
ListView - ViewHolder > RecyclerView + LazyColumn
Memory leaks > Memory leaks still exists
Running in background > Coroutine - RxJava
We still have things to optimized.
They are just different.
@snnkzk
59
I hope you have this chart in your next release
@snnkzk
Thank you
github.com/kozaxinan linkedin.com/in/sinankozak strava.com/athletes/sinankozak
@snnkzk
Do you have any questions?

More Related Content

PDF
Unblocking The Main Thread_ Solving ANRs and Frozen Frames.pdf
PDF
Unblocking The Main Thread Solving ANRs and Frozen Frames
PPTX
[충격] 당신의 안드로이드 앱이 느린 이유가 있다??!
PDF
Profiling tools and Android Performance patterns
PPTX
Android Performance Tips & Tricks
PPTX
Сергей Жук "Android Performance Tips & Tricks"
PDF
Performance optimization for Android
PPTX
Android performance
Unblocking The Main Thread_ Solving ANRs and Frozen Frames.pdf
Unblocking The Main Thread Solving ANRs and Frozen Frames
[충격] 당신의 안드로이드 앱이 느린 이유가 있다??!
Profiling tools and Android Performance patterns
Android Performance Tips & Tricks
Сергей Жук "Android Performance Tips & Tricks"
Performance optimization for Android
Android performance

Similar to Unblocking The Main Thread - Solving ANRs and Frozen Frames (20)

PDF
10 ways to improve your Android app performance
PPTX
Optimisation and performance in Android
PPTX
Andromance - Android Performance
PPTX
Optimizing Apps for Better Performance
PDF
Performance: How to build an app instead of slideshow
PDF
14 Tips On How To Improve Android App Performance
PPTX
Android app performance
PDF
Memory Leaks in Android Applications
PDF
Using Automatic Refactoring to Improve Energy Efficiency of Android Apps
PDF
Characterizing and detecting performance bugs for smartphone applications
PDF
Android programming -_pushing_the_limits
PDF
Big Trouble in Little Networks, new and improved
PDF
performance optimization: Memory
PDF
Sidiq Permana - Building For The Next Billion Users
PDF
Android UI Tips, Tricks and Techniques
PDF
Android UI Development: Tips, Tricks, and Techniques
PPTX
Optimizing apps for better performance extended
PPTX
Android Performance Best Practices
PPTX
Getting Intimate with Images on Android with James Halpern
PDF
Android development first steps
10 ways to improve your Android app performance
Optimisation and performance in Android
Andromance - Android Performance
Optimizing Apps for Better Performance
Performance: How to build an app instead of slideshow
14 Tips On How To Improve Android App Performance
Android app performance
Memory Leaks in Android Applications
Using Automatic Refactoring to Improve Energy Efficiency of Android Apps
Characterizing and detecting performance bugs for smartphone applications
Android programming -_pushing_the_limits
Big Trouble in Little Networks, new and improved
performance optimization: Memory
Sidiq Permana - Building For The Next Billion Users
Android UI Tips, Tricks and Techniques
Android UI Development: Tips, Tricks, and Techniques
Optimizing apps for better performance extended
Android Performance Best Practices
Getting Intimate with Images on Android with James Halpern
Android development first steps
Ad

Recently uploaded (20)

PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
Digital Logic Computer Design lecture notes
PDF
composite construction of structures.pdf
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
PPT on Performance Review to get promotions
DOCX
573137875-Attendance-Management-System-original
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Welding lecture in detail for understanding
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
Geodesy 1.pptx...............................................
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
additive manufacturing of ss316l using mig welding
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Sustainable Sites - Green Building Construction
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Model Code of Practice - Construction Work - 21102022 .pdf
Digital Logic Computer Design lecture notes
composite construction of structures.pdf
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPT on Performance Review to get promotions
573137875-Attendance-Management-System-original
Foundation to blockchain - A guide to Blockchain Tech
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Welding lecture in detail for understanding
CH1 Production IntroductoryConcepts.pptx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
Geodesy 1.pptx...............................................
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Internet of Things (IOT) - A guide to understanding
additive manufacturing of ss316l using mig welding
Embodied AI: Ushering in the Next Era of Intelligent Systems
Sustainable Sites - Green Building Construction
R24 SURVEYING LAB MANUAL for civil enggi
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Ad

Unblocking The Main Thread - Solving ANRs and Frozen Frames