SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

En vedette

Michael North "The Road to Native Web Components"
Michael North "The Road to Native Web Components"Michael North "The Road to Native Web Components"
Michael North "The Road to Native Web Components"
Fwdays
 
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
Сергей Яковлев "Phalcon 2 - стабилизация и производительность"
Fwdays
 
4 puchnina.pptx
4 puchnina.pptx4 puchnina.pptx
4 puchnina.pptx
Fwdays
 
"Красная книга веб-разработчика" Виктор Полищук
"Красная книга веб-разработчика" Виктор Полищук"Красная книга веб-разработчика" Виктор Полищук
"Красная книга веб-разработчика" Виктор Полищук
Fwdays
 

En vedette (20)

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

Similaire à Сергей Жук "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
 

Similaire à Сергей Жук "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
 
Titanium appcelerator best practices
Titanium appcelerator best practicesTitanium appcelerator best practices
Titanium appcelerator best practices
 
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
 

Plus de Fwdays

Plus de Fwdays (20)

"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y..."How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
 
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
 
"Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl..."Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl...
 
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T..."How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
 
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ..."The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
 
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu..."[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
 
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care..."[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
 
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"..."4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
 
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout", Anast...
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout",  Anast..."Reconnecting with Purpose: Rediscovering Job Interest after Burnout",  Anast...
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout", Anast...
 
"Mentoring 101: How to effectively invest experience in the success of others...
"Mentoring 101: How to effectively invest experience in the success of others..."Mentoring 101: How to effectively invest experience in the success of others...
"Mentoring 101: How to effectively invest experience in the success of others...
 
"Mission (im) possible: How to get an offer in 2024?", Oleksandra Myronova
"Mission (im) possible: How to get an offer in 2024?",  Oleksandra Myronova"Mission (im) possible: How to get an offer in 2024?",  Oleksandra Myronova
"Mission (im) possible: How to get an offer in 2024?", Oleksandra Myronova
 
"Why have we learned how to package products, but not how to 'package ourselv...
"Why have we learned how to package products, but not how to 'package ourselv..."Why have we learned how to package products, but not how to 'package ourselv...
"Why have we learned how to package products, but not how to 'package ourselv...
 
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin..."How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
 

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Сергей Жук "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

Notes de l'éditeur

  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: удобно собирает статистику по времени выполнения каждого метода на различных девайсах Не забудьте убрать все свои логи перед выкатом в продакшен.