SlideShare a Scribd company logo
1 of 25
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

Viewers also liked

Unit testing in android
Unit testing in androidUnit testing in android
Unit testing in android
Li-Wei Cheng
 

Viewers also liked (20)

Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
Introduction to android testing - oscon 2012
Introduction to android testing - oscon 2012Introduction to android testing - oscon 2012
Introduction to android testing - oscon 2012
 
Testing for Android: When, Where, and How to Successfully Use Test Automation
Testing for Android: When, Where, and How to Successfully Use Test AutomationTesting for Android: When, Where, and How to Successfully Use Test Automation
Testing for Android: When, Where, and How to Successfully Use Test Automation
 
Android Testing: An Overview
Android Testing: An OverviewAndroid Testing: An Overview
Android Testing: An Overview
 
Testing Android Application, Droidcon Torino
Testing Android Application, Droidcon TorinoTesting Android Application, Droidcon Torino
Testing Android Application, Droidcon Torino
 
Inside Android Testing
Inside Android TestingInside Android Testing
Inside Android Testing
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversing
 
Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016
Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016
Unit Testing on Android: why and how? DevFest Romania, Bucharest 2016
 
Testing Android applications with Maveryx
Testing Android applications with MaveryxTesting Android applications with Maveryx
Testing Android applications with Maveryx
 
Android testing
Android testingAndroid testing
Android testing
 
Android Testing, Why So Hard?!
Android Testing, Why So Hard?!Android Testing, Why So Hard?!
Android Testing, Why So Hard?!
 
Testing Android
Testing AndroidTesting Android
Testing Android
 
Testing With Open Source
Testing With Open SourceTesting With Open Source
Testing With Open Source
 
Unit testing in android
Unit testing in androidUnit testing in android
Unit testing in android
 
Unit testing on Android (Droidcon Dubai 2015)
Unit testing on Android (Droidcon Dubai 2015)Unit testing on Android (Droidcon Dubai 2015)
Unit testing on Android (Droidcon Dubai 2015)
 
Unit testing and Android
Unit testing and AndroidUnit testing and Android
Unit testing and Android
 
Mobile Performance Testing - Best Practices
Mobile Performance Testing - Best PracticesMobile Performance Testing - Best Practices
Mobile Performance Testing - Best Practices
 
Rapid Android Application Security Testing
Rapid Android Application Security TestingRapid Android Application Security Testing
Rapid Android Application Security Testing
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 
Testing on Android
Testing on AndroidTesting on Android
Testing on Android
 

Similar to Android Performance Tips & Tricks

Matteo Gazzurelli - Introduction to Android Development - Have a break edition
Matteo Gazzurelli - Introduction to Android Development - Have a break editionMatteo Gazzurelli - Introduction to Android Development - Have a break edition
Matteo Gazzurelli - Introduction to Android Development - Have a break edition
DuckMa
 
Project Presentation - First Spring
Project Presentation - First SpringProject Presentation - First Spring
Project Presentation - First Spring
Didac Montero
 
Beating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett DuncavageBeating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett Duncavage
Xamarin
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
catherinewall
 

Similar to Android Performance Tips & Tricks (20)

TU-Charts Project - First Spring
TU-Charts Project - First SpringTU-Charts Project - First Spring
TU-Charts Project - First Spring
 
First spring
First springFirst spring
First spring
 
Matteo Gazzurelli - Introduction to Android Development - Have a break edition
Matteo Gazzurelli - Introduction to Android Development - Have a break editionMatteo Gazzurelli - Introduction to Android Development - Have a break edition
Matteo Gazzurelli - Introduction to Android Development - Have a break edition
 
Android : How Do I Code Thee?
Android : How Do I Code Thee?Android : How Do I Code Thee?
Android : How Do I Code Thee?
 
Mind your App Footprint 🐾⚡️🌱 (@FlutterConn 2023)
Mind your App Footprint 🐾⚡️🌱 (@FlutterConn 2023)Mind your App Footprint 🐾⚡️🌱 (@FlutterConn 2023)
Mind your App Footprint 🐾⚡️🌱 (@FlutterConn 2023)
 
Being Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentBeing Epic: Best Practices for Android Development
Being Epic: Best Practices for Android Development
 
Profiling tools and Android Performance patterns
Profiling tools and Android Performance patternsProfiling tools and Android Performance patterns
Profiling tools and Android Performance patterns
 
An Introduction To Android
An Introduction To AndroidAn Introduction To Android
An Introduction To Android
 
Matteo Gazzurelli - Andorid introduction - Google Dev Fest 2013
Matteo Gazzurelli - Andorid introduction - Google Dev Fest 2013Matteo Gazzurelli - Andorid introduction - Google Dev Fest 2013
Matteo Gazzurelli - Andorid introduction - Google Dev Fest 2013
 
Using Automatic Refactoring to Improve Energy Efficiency of Android Apps
Using Automatic Refactoring to Improve Energy Efficiency of Android AppsUsing Automatic Refactoring to Improve Energy Efficiency of Android Apps
Using Automatic Refactoring to Improve Energy Efficiency of Android Apps
 
Project Presentation - First Spring
Project Presentation - First SpringProject Presentation - First Spring
Project Presentation - First Spring
 
Presentation1
Presentation1Presentation1
Presentation1
 
Beating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett DuncavageBeating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett Duncavage
 
How to deal with Fragmentation on Android
How to deal with Fragmentation on AndroidHow to deal with Fragmentation on Android
How to deal with Fragmentation on Android
 
Pertemuan 3 pm
Pertemuan 3   pmPertemuan 3   pm
Pertemuan 3 pm
 
Raising ux bar with offline first design
Raising ux bar with offline first designRaising ux bar with offline first design
Raising ux bar with offline first design
 
Android class provider in mumbai
Android class provider in mumbaiAndroid class provider in mumbai
Android class provider in mumbai
 
JDK Tools For Performance Diagnostics
JDK Tools For Performance DiagnosticsJDK Tools For Performance Diagnostics
JDK Tools For Performance Diagnostics
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
 
Intro to android (gdays)
Intro to android (gdays)Intro to android (gdays)
Intro to android (gdays)
 

Recently uploaded

CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
anilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
anilsa9823
 

Recently uploaded (7)

Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 

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

  1. Не будем писать код -- Много кода есть у индусов Магии не будет, будет много простого и правильного
  2. Каждый объект – как минимум 8 байт + Специфичные реализации Android, где нет лишних методов – но и нет реализации Map
  3. ProGuard: в некоторых случаях может привести enum к int
  4. Крешили и Core2 и galaxy s3. Может, на маленькой картинке это работает ок и можно забить
  5. Отдельный случай – когда работаете с ViewPager – и держите в памяти 3-5 экранов – тогда тормоза заметны и на быстром устройстве
  6. Is Android layout really exponentially hard? discussion http://stackoverflow.com/questions/17493819/is-android-layout-really-exponentially-hard Also sometimes on LinearLayouts with weight
  7. <style name="AppBaseTheme" parent="android:Theme.Holo.NoActionBar">     <item name="android:windowBackground">@color/red</item> </style>
  8. Первое, что приходит в голову, когда нужно показать часть 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().
  9. Весело – это когда заказчик просит приложение как iOS, забывая, что айфоны стоят в разы дороже среднего андроида
  10. Ещё – случай со смартфонами Huawei и неправильными лого
  11. Дорого, хлопотно Вопрос в том – готов ли ваш заказчик за это платить. Цукерберг хвастался FBLight – меньше 1Мб
  12. Есть такой соблазн Якобы понижает вероятность OutOfMemory
  13. Встраивается в ваше приложение, инициализируется одной строчкой кода, Подключается в gradle в режимах debugCompile и releaseCompile (пустая)
  14. Пьер из команды Square в начале мая релизнул. 3.5К звёзд в гитхабе за месяц Удобно при тестировании приложения – больше не нужно подключать и ручками сливать дампы: удобно для тестировщиков
  15. StrictMode to catch accidental disk or network access on the application's main thread, NewRelic: удобно собирает статистику по времени выполнения каждого метода на различных девайсах Не забудьте убрать все свои логи перед выкатом в продакшен.