Android Performance Tips & Tricks
Sergii Zhuk
Android Developer at DAXX BV
Kyiv, FrameworksDays Android Saturday, 2015-06-06 1
Agenda
• Effective Java in Android
• Layouts and UI
• Proper Use of Resources
• Dev Tools and Measuring Performance
2
Effective Java in Android
• Avoid using Floating-Point
• Prefer primitives and primitive-backed data
structures (ArrayMap, SparseArray)
• Two parallel (int) arrays are better than array
(int,int)
3
Effective Java in Android
• System.arraycopy() is about 9x faster than a
hand-coded loop
• Make your method static: invocations will be
about 15%-20% faster
• Do not use Enums
WAT??
 @IntDef annotation
4
Supplying Scaled Drawables
• Why not to supply a single xhdpi image as blurred
background for the screen?
• Rendering performance will decrease because
device should scale your image during app
execution
• Such operation requires extra memory for Bitmap
native processing, potential source of
OutOfMemoryError
5
Make Your Layouts Flat
• Inflating layout is a top-down traversal of the
view tree
• Hierarchy Viewer (Android SDK) allows to
analyze layout while your application is
running
6
“Heavy” ViewGroups
• RelativeLayout requires two measurement passes to
ensure that it has handled all of the layout relationships
• The same is valid for LinearLayout with layout weights
• If one of the children of ViewGroups shown above is again
RelativeLayout or LinearLayout with weights – four
measurements passes will be required for sub-hierarchy
• GridLayout could be good solution in some cases (API 14+)
7
GridLayout example
8
Splash Screen Effect
• Show a blank window constructed with the
application theme, including specified
background drawable while application is
starting
• Behavior is provided by OS
9
Splash Screen Effect
10
ViewStub
• A lightweight view with no dimension and
doesn’t draw anything or participate in the
layout
• Use ViewStub as a “lazy include” for sub-
hierarchies that can be optionally inflated
later.
11
Develop for the Low End
• Devices distribution in the world
• Most of users could have lower-end devices
than yours
• Use ActivityManager.isLowRamDevice() to
detect if device in the class of a 512MB RAM
and/or about a 800x480 screen [API 19+]
12
13
Develop for the Low End
* More details at my Stackoverflow.com question
Nexus 4 (Genymotion emu)
and other devices
Lenovo P780 with Android 4.2.1
Remove unused resources
• Lint (Android SDK): will highlight these resources
• Android-resource-remover (consumes Lint
output)
• Gradle:
14
buildTypes {
release {
minifyEnabled true
shrinkResources true
}
}
Multiple APKs on Play Store
• Different APKs for your app that are each
targeted to different device configurations
• Have same app listing on Google Play and must
share the same package name and be signed with
the same release key
• Recommended to use multiple APKs only when
your APK is too large (> 50MB)
15
Gradle Plugin: APK splits
android {
...
splits {
density {
enable true
reset()
exclude "ldpi", "tvdpi", "xxxhdpi"
}
}
16
WARN: you will need to set different version code for each APK file
Developer Options On Your Device
17
Developer Options On Your Device
18
Avoid Requesting a Large Heap
• Requesting a larger heap may be necessary in
some rare situations like media content
• android:largeHeap=“true” result: less memory
to be available for other apps, necessitating
them being killed and restarted
• android:largeHeap seems to be not enough
documented
19
Memory Leaks
• If a chain of references holds an object in
memory after the end of its expected lifetime
• Old approach:
Dump  Fix header  MAT  Find leak
• New approach: LeakCanary will notify you
20
LeakCanary
21
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1'
}
public class ExampleApplication extends Application {
@Override public void onCreate() {
super.onCreate();
LeakCanary.install(this);
}
}
LeakCanary
22
* Sometimes you still need MAT
In-app performance check
• StrictMode
• Google’s profiling tools: Traceview &
dmtracedump
• Hugo by Jake Wharton
• Tools like NewRelic to show bottlenecks in
response time
23
References
• http://developer.android.com/training/articles/perf-tips.html
• Chet Haase at Medium: Developing for Android (parts 1-5)
• Memory leaks in Android (in Russian)
• Android Performance Case Study by Romain Guy
• Is Android layout really exponentially hard? SO discussion
• Pro Android Apps Performance Optimization by Herv Guihot
• Eric Lafortune talk on MCE2015 Conference
• Cyril Mottier blog
• Taylor Ling blog
• Romain Guy blog
• Android Performance Patterns (YouTube and G+)
• DOU.ua Android Digest 
24
Thank you!
@sergiizhuk
sergey.public@gmail.com
http://ua.linkedin.com/in/sergiizhuk
25

More Related Content

PPTX
Android Applications Development: A Quick Start Guide
PPT
Operational dashboard for apache cloud stack
PPTX
Web gl api to render interactive graphics in html
PDF
Александр Махомет "Feature Flags. Уменьшаем риски при выпуске изменений"
PDF
Андрей Шумада | Tank.ly
PDF
"После OOD: как моделировать предметную область в пост-объектном мире" Руслан...
PDF
Евгений Жарков AngularJS: Good parts
PDF
Павел Тайкало: "Optimistic Approach : How to show results instead spinners wi...
Android Applications Development: A Quick Start Guide
Operational dashboard for apache cloud stack
Web gl api to render interactive graphics in html
Александр Махомет "Feature Flags. Уменьшаем риски при выпуске изменений"
Андрей Шумада | Tank.ly
"После OOD: как моделировать предметную область в пост-объектном мире" Руслан...
Евгений Жарков AngularJS: Good parts
Павел Тайкало: "Optimistic Approach : How to show results instead spinners wi...

Viewers also liked (20)

PDF
Алексей Волков "Интерактивные декларативные графики на React+D3"
PPT
"Spring Boot. Boot up your development" Сергей Моренец
PDF
Евгений Обрезков "Behind the terminal"
PDF
Fighting Fat Models (Богдан Гусев)
PDF
Алексей Рыбаков: "Wearable OS год спустя: Apple Watch 2.0, Android Wear 5.1.1...
PPTX
"Query Execution: Expectation - Reality (Level 300)" Денис Резник
PDF
Илья Прукко: "Как дизайнеру не становиться художником"
PDF
"Frameworks in 2015" Андрей Листочкин
PDF
Светлана Старикова "Building a self-managing team: why you should not have e...
PDF
Lightweight APIs in mRuby (Михаил Бортник)
PDF
Анатолий Попель: "Формы оплаты и платёжные шлюзы"
PDF
Александр Воронов | Building CLI with Swift
PDF
Скрам и Канбан: применимость самых распространенных методов организации умств...
PDF
Michael North "The Road to Native Web Components"
PDF
Designing for Privacy
PDF
Анастасия Войтова: "Building profanity filters on mobile: clbuttic sh!t"
PPTX
Трансформация команды: от инди разработки к играм с коммерческой успешностью
PDF
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
PDF
4 puchnina.pptx
PPTX
"Красная книга веб-разработчика" Виктор Полищук
Алексей Волков "Интерактивные декларативные графики на React+D3"
"Spring Boot. Boot up your development" Сергей Моренец
Евгений Обрезков "Behind the terminal"
Fighting Fat Models (Богдан Гусев)
Алексей Рыбаков: "Wearable OS год спустя: Apple Watch 2.0, Android Wear 5.1.1...
"Query Execution: Expectation - Reality (Level 300)" Денис Резник
Илья Прукко: "Как дизайнеру не становиться художником"
"Frameworks in 2015" Андрей Листочкин
Светлана Старикова "Building a self-managing team: why you should not have e...
Lightweight APIs in mRuby (Михаил Бортник)
Анатолий Попель: "Формы оплаты и платёжные шлюзы"
Александр Воронов | Building CLI with Swift
Скрам и Канбан: применимость самых распространенных методов организации умств...
Michael North "The Road to Native Web Components"
Designing for Privacy
Анастасия Войтова: "Building profanity filters on mobile: clbuttic sh!t"
Трансформация команды: от инди разработки к играм с коммерческой успешностью
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
4 puchnina.pptx
"Красная книга веб-разработчика" Виктор Полищук

Similar to Сергей Жук "Android Performance Tips & Tricks" (20)

PDF
Profiling tools and Android Performance patterns
PPTX
Android app performance
PDF
Android development first steps
PPTX
Android Performance Best Practices
PDF
Android UI Tips, Tricks and Techniques
PDF
Android UI Development: Tips, Tricks, and Techniques
PPTX
[충격] 당신의 안드로이드 앱이 느린 이유가 있다??!
PPTX
Optimisation and performance in Android
PDF
Android, the life of your app
PDF
Beating Android Fragmentation, Brett Duncavage
PPT
Part 2 android application development 101
PDF
10 ways to improve your Android app performance
PDF
Android dev tips
PDF
Beating Android Fragmentation
PDF
Sidiq Permana - Building For The Next Billion Users
PPTX
How to create Great App
PPTX
Technology and Android.pptx
PDF
The Good, the Bad and the Ugly things to do with android
PDF
Android development - the basics, MFF UK, 2014
PDF
Android development - the basics, MFF UK, 2012
Profiling tools and Android Performance patterns
Android app performance
Android development first steps
Android Performance Best Practices
Android UI Tips, Tricks and Techniques
Android UI Development: Tips, Tricks, and Techniques
[충격] 당신의 안드로이드 앱이 느린 이유가 있다??!
Optimisation and performance in Android
Android, the life of your app
Beating Android Fragmentation, Brett Duncavage
Part 2 android application development 101
10 ways to improve your Android app performance
Android dev tips
Beating Android Fragmentation
Sidiq Permana - Building For The Next Billion Users
How to create Great App
Technology and Android.pptx
The Good, the Bad and the Ugly things to do with android
Android development - the basics, MFF UK, 2014
Android development - the basics, MFF UK, 2012

More from Fwdays (20)

PDF
"Mastering UI Complexity: State Machines and Reactive Patterns at Grammarly",...
PDF
"Effect, Fiber & Schema: tactical and technical characteristics of Effect.ts"...
PPTX
"Computer Use Agents: From SFT to Classic RL", Maksym Shamrai
PPTX
"Як ми переписали Сільпо на Angular", Євген Русаков
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
PDF
"Validation and Observability of AI Agents", Oleksandr Denisyuk
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
PPTX
"Co-Authoring with a Machine: What I Learned from Writing a Book on Generativ...
PPTX
"Human-AI Collaboration Models for Better Decisions, Faster Workflows, and Cr...
PDF
"AI is already here. What will happen to your team (and your role) tomorrow?"...
PPTX
"Is it worth investing in AI in 2025?", Alexander Sharko
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
PDF
"Scaling in space and time with Temporal", Andriy Lupa.pdf
PDF
"Database isolation: how we deal with hundreds of direct connections to the d...
PDF
"Scaling in space and time with Temporal", Andriy Lupa .pdf
PPTX
"Provisioning via DOT-Chain: from catering to drone marketplaces", Volodymyr ...
PPTX
" Observability with Elasticsearch: Best Practices for High-Load Platform", A...
PPTX
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
PPTX
"Istio Ambient Mesh in production: our way from Sidecar to Sidecar-less",Hlib...
"Mastering UI Complexity: State Machines and Reactive Patterns at Grammarly",...
"Effect, Fiber & Schema: tactical and technical characteristics of Effect.ts"...
"Computer Use Agents: From SFT to Classic RL", Maksym Shamrai
"Як ми переписали Сільпо на Angular", Євген Русаков
"AI Transformation: Directions and Challenges", Pavlo Shaternik
"Validation and Observability of AI Agents", Oleksandr Denisyuk
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
"Co-Authoring with a Machine: What I Learned from Writing a Book on Generativ...
"Human-AI Collaboration Models for Better Decisions, Faster Workflows, and Cr...
"AI is already here. What will happen to your team (and your role) tomorrow?"...
"Is it worth investing in AI in 2025?", Alexander Sharko
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Database isolation: how we deal with hundreds of direct connections to the d...
"Scaling in space and time with Temporal", Andriy Lupa .pdf
"Provisioning via DOT-Chain: from catering to drone marketplaces", Volodymyr ...
" Observability with Elasticsearch: Best Practices for High-Load Platform", A...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"Istio Ambient Mesh in production: our way from Sidecar to Sidecar-less",Hlib...

Recently uploaded (20)

PDF
Child-friendly e-learning for artificial intelligence education in Indonesia:...
PDF
Addressing the challenges of harmonizing law and artificial intelligence tech...
PDF
Secure Java Applications against Quantum Threats
PDF
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
PDF
Human Computer Interaction Miterm Lesson
PPTX
Report in SIP_Distance_Learning_Technology_Impact.pptx
PDF
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
PDF
Domain-specific knowledge and context in large language models: challenges, c...
PDF
State of AI in Business 2025 - MIT NANDA
PDF
Ebook - The Future of AI A Comprehensive Guide.pdf
PDF
Decision Optimization - From Theory to Practice
PDF
【AI論文解説】高速・高品質な生成を実現するFlow Map Models(Part 1~3)
PPTX
Information-Technology-in-Human-Society.pptx
PPTX
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
PDF
Altius execution marketplace concept.pdf
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
Optimizing bioinformatics applications: a novel approach with human protein d...
PDF
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
PDF
NewMind AI Journal Monthly Chronicles - August 2025
PPTX
Information-Technology-in-Human-Society (2).pptx
Child-friendly e-learning for artificial intelligence education in Indonesia:...
Addressing the challenges of harmonizing law and artificial intelligence tech...
Secure Java Applications against Quantum Threats
EGCB_Solar_Project_Presentation_and Finalcial Analysis.pdf
Human Computer Interaction Miterm Lesson
Report in SIP_Distance_Learning_Technology_Impact.pptx
FASHION-DRIVEN TEXTILES AS A CRYSTAL OF A NEW STREAM FOR STAKEHOLDER CAPITALI...
Domain-specific knowledge and context in large language models: challenges, c...
State of AI in Business 2025 - MIT NANDA
Ebook - The Future of AI A Comprehensive Guide.pdf
Decision Optimization - From Theory to Practice
【AI論文解説】高速・高品質な生成を実現するFlow Map Models(Part 1~3)
Information-Technology-in-Human-Society.pptx
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
Altius execution marketplace concept.pdf
Presentation - Principles of Instructional Design.pptx
Optimizing bioinformatics applications: a novel approach with human protein d...
The Digital Engine Room: Unlocking APAC’s Economic and Digital Potential thro...
NewMind AI Journal Monthly Chronicles - August 2025
Information-Technology-in-Human-Society (2).pptx

Сергей Жук "Android Performance Tips & Tricks"

  • 1. Android Performance Tips & Tricks Sergii Zhuk Android Developer at DAXX BV Kyiv, FrameworksDays Android Saturday, 2015-06-06 1
  • 2. Agenda • Effective Java in Android • Layouts and UI • Proper Use of Resources • Dev Tools and Measuring Performance 2
  • 3. Effective Java in Android • Avoid using Floating-Point • Prefer primitives and primitive-backed data structures (ArrayMap, SparseArray) • Two parallel (int) arrays are better than array (int,int) 3
  • 4. Effective Java in Android • System.arraycopy() is about 9x faster than a hand-coded loop • Make your method static: invocations will be about 15%-20% faster • Do not use Enums WAT??  @IntDef annotation 4
  • 5. Supplying Scaled Drawables • Why not to supply a single xhdpi image as blurred background for the screen? • Rendering performance will decrease because device should scale your image during app execution • Such operation requires extra memory for Bitmap native processing, potential source of OutOfMemoryError 5
  • 6. Make Your Layouts Flat • Inflating layout is a top-down traversal of the view tree • Hierarchy Viewer (Android SDK) allows to analyze layout while your application is running 6
  • 7. “Heavy” ViewGroups • RelativeLayout requires two measurement passes to ensure that it has handled all of the layout relationships • The same is valid for LinearLayout with layout weights • If one of the children of ViewGroups shown above is again RelativeLayout or LinearLayout with weights – four measurements passes will be required for sub-hierarchy • GridLayout could be good solution in some cases (API 14+) 7
  • 9. Splash Screen Effect • Show a blank window constructed with the application theme, including specified background drawable while application is starting • Behavior is provided by OS 9
  • 11. ViewStub • A lightweight view with no dimension and doesn’t draw anything or participate in the layout • Use ViewStub as a “lazy include” for sub- hierarchies that can be optionally inflated later. 11
  • 12. Develop for the Low End • Devices distribution in the world • Most of users could have lower-end devices than yours • Use ActivityManager.isLowRamDevice() to detect if device in the class of a 512MB RAM and/or about a 800x480 screen [API 19+] 12
  • 13. 13 Develop for the Low End * More details at my Stackoverflow.com question Nexus 4 (Genymotion emu) and other devices Lenovo P780 with Android 4.2.1
  • 14. Remove unused resources • Lint (Android SDK): will highlight these resources • Android-resource-remover (consumes Lint output) • Gradle: 14 buildTypes { release { minifyEnabled true shrinkResources true } }
  • 15. Multiple APKs on Play Store • Different APKs for your app that are each targeted to different device configurations • Have same app listing on Google Play and must share the same package name and be signed with the same release key • Recommended to use multiple APKs only when your APK is too large (> 50MB) 15
  • 16. Gradle Plugin: APK splits android { ... splits { density { enable true reset() exclude "ldpi", "tvdpi", "xxxhdpi" } } 16 WARN: you will need to set different version code for each APK file
  • 17. Developer Options On Your Device 17
  • 18. Developer Options On Your Device 18
  • 19. Avoid Requesting a Large Heap • Requesting a larger heap may be necessary in some rare situations like media content • android:largeHeap=“true” result: less memory to be available for other apps, necessitating them being killed and restarted • android:largeHeap seems to be not enough documented 19
  • 20. Memory Leaks • If a chain of references holds an object in memory after the end of its expected lifetime • Old approach: Dump  Fix header  MAT  Find leak • New approach: LeakCanary will notify you 20
  • 21. LeakCanary 21 dependencies { debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1' } public class ExampleApplication extends Application { @Override public void onCreate() { super.onCreate(); LeakCanary.install(this); } }
  • 23. In-app performance check • StrictMode • Google’s profiling tools: Traceview & dmtracedump • Hugo by Jake Wharton • Tools like NewRelic to show bottlenecks in response time 23
  • 24. References • http://developer.android.com/training/articles/perf-tips.html • Chet Haase at Medium: Developing for Android (parts 1-5) • Memory leaks in Android (in Russian) • Android Performance Case Study by Romain Guy • Is Android layout really exponentially hard? SO discussion • Pro Android Apps Performance Optimization by Herv Guihot • Eric Lafortune talk on MCE2015 Conference • Cyril Mottier blog • Taylor Ling blog • Romain Guy blog • Android Performance Patterns (YouTube and G+) • DOU.ua Android Digest  24

Editor's Notes

  • #3: Не будем писать код -- Много кода есть у индусов Магии не будет, будет много простого и правильного
  • #4: Каждый объект – как минимум 8 байт + Специфичные реализации Android, где нет лишних методов – но и нет реализации Map
  • #5: ProGuard: в некоторых случаях может привести enum к int
  • #6: Крешили и Core2 и galaxy s3. Может, на маленькой картинке это работает ок и можно забить
  • #7: Отдельный случай – когда работаете с ViewPager – и держите в памяти 3-5 экранов – тогда тормоза заметны и на быстром устройстве
  • #8: Is Android layout really exponentially hard? discussion http://stackoverflow.com/questions/17493819/is-android-layout-really-exponentially-hard Also sometimes on LinearLayouts with weight
  • #10: <style name="AppBaseTheme" parent="android:Theme.Holo.NoActionBar">     <item name="android:windowBackground">@color/red</item> </style>
  • #12: Первое, что приходит в голову, когда нужно показать часть UI позже: сделать View.GONE ViewStub : нет размеров, ничего не рисует When inflate() is invoked, the ViewStub is replaced by the inflated View and the inflated View is returned. This lets applications get a reference to the inflated View without executing an extra findViewById().
  • #13: Весело – это когда заказчик просит приложение как iOS, забывая, что айфоны стоят в разы дороже среднего андроида
  • #14: Ещё – случай со смартфонами Huawei и неправильными лого
  • #16: Дорого, хлопотно Вопрос в том – готов ли ваш заказчик за это платить. Цукерберг хвастался FBLight – меньше 1Мб
  • #20: Есть такой соблазн Якобы понижает вероятность OutOfMemory
  • #22: Встраивается в ваше приложение, инициализируется одной строчкой кода, Подключается в gradle в режимах debugCompile и releaseCompile (пустая)
  • #23: Пьер из команды Square в начале мая релизнул. 3.5К звёзд в гитхабе за месяц Удобно при тестировании приложения – больше не нужно подключать и ручками сливать дампы: удобно для тестировщиков
  • #24: StrictMode to catch accidental disk or network access on the application's main thread, NewRelic: удобно собирает статистику по времени выполнения каждого метода на различных девайсах Не забудьте убрать все свои логи перед выкатом в продакшен.