SlideShare uma empresa Scribd logo
1 de 31
Baixar para ler offline
Profiling tools and Android
performance patterns
Providing a good user experience
The mobile agency for food retail
Jonathan Maldonado Contreras
@Jonazan2
Android Developer
“Mobile internet will become
the most important medium
in people's lives.”
Founded in 2002
• Adding emotion to transactional loyalty
• 120 developers, designers & specialists, HQ in Amsterdam, NL
• Operating in 3 continents: Europe, North America and Asia
The magic happens at the intersection
IceMobile
Creativity Technology
Performance is about user experience
Apps nowadays are all about fancy animations, complex transitions and
custom views
And the experience must be the most robust and similar as possible in any
device
CPU GPU
BatteryMemory Network
GPU profiling
Understanding the rendering pipeline
Our apps must run at 60 frames per second
————
1000ms
60 frames
= 16,66ms per frame
In this 16,66 ms we have to:
• Do any computation
• Update our screen to the GPU
• Draw the screen
• Deal with GC events
Settings Developer options
Profile GPU rendering Show on
bars
• Green: 16ms barrier
• Blue: create and update the views
display list
• Purple (4.0+): time transferring
resources to rendering thread
• Red: android 2d renderer in OpenGL
• Orange: CPU’s waiting time
Profiling GPU rendering
16ms
A lot of frame drops? Check for:
• Unnecessary invalidations that may trigger a cascade of invalidations.
(GPU View Updates can help profiling)
• RelativeLayouts in a high hierarchy level 

• Nested weights in LinearLayouts

• Unnecessary overdraw

• Customs views not properly made
Patterns to avoid bad performance
• Use <merge> as root in your layout
• Avoid unnecessary layouts
• Don’t make allocations or heavy operations in OnDraw
• Remove unnecessary calls to invalidate()
• Consider creating your own ViewGroup
invalidate() hierarchy invalidations onDraw()
Patterns for custom views
Make them as simple as possible
OnMeasure/OnLayout…
• True color: No overdraw
• Blue: Overdrawn once
• Green: Overdrawn twice
• Pink: Overdrawn three times
• Red: Overdrawn four times
Profiling GPU overdraw
• Depends on the GPU architecture: Nvidia’s Tegra is different than
ImaginationTech’s SGX and so on.
• Hierarchy Viewer (ViewServer by @RomainGuy for any phone) and
Tracer
Steps to follow when you have too much overdraw:
• Simplify your drawables
• Use 9patch with transparent parts
• Caution with setting alpha in your views
About overdraw
Memory profiling
Understanding the garbage collector
Displays:
• Free and allocated memory in real time

• GC events

Allows us:

• Cause GC events

• Start the allocation tracker

• Dump the Java Heap
Memory monitor
• If our app is using an excessive amount of memory
• When your app is running out of memory
• If a GC event occurs and the memory is not properly free
• If the app is slow due to a vast amount of GC events, a GC cascade
What the memory monitor can tell us
Runtime
totalMemory()
maxMemory()
current heap size (bytes)
max heap size (bytes)
Heap dump
We can use the heap dump to check:
• The current memory state for our app
• The amount of objects
• Type of those objects
• Hierarchy between references
Allocation Tracker
Allocation tracker displays:
• Which classes and methods are allocating which objects
• It’s possible to see allocated memory in each thread of your app
Allocation
tracker
Heap
Memory
monitor
All integrated within Android Studio
Using our profiling tools in Android Studio:
1. Open memory monitor before opening an activity
2. Start the allocation tracker and dump the heap after loading the
activity
3. Go to a different activity and force a GC event
4. Stop allocation tracker, dump the heap...and investigate
Discovering memory leaks
Allocation space in the HEAP
* The allocation space is different between Dalvik andART
Allocation space in the HEAP
GC EVENT
Leaked
Memory
Leaked
Memory
Allocated
Memory
Allocated
Memory
Needed
Memory
Needed
Memory
OUT OF
MEMORY
ERROR
Don’t leak contexts in inner classes.

Don’t leak views inside an activity.

Don’t use WeakHashMap as cache. Only the keys are weak references.

Use the proper context. AppContext != View context
Use static classes instead of Inner classes.
Use WeakReference or SoftReference.
Release callbacks in a proper way (handlers, observers...)
Avoiding memory leaks
The principal cause of GC cascades is memory churn: high number of
objects get allocated and potentially free in a short period of time.
GC cascades: discovering and avoiding memory
churn
16ms 16ms 16ms 16ms
GCUPDATE GCUPDATE UP D
Frame
drop
GC ATE
draw draw draw
• Don’t allocate a large amount of unnecessary objects
• Immutable classes: String
• Autoboxing: Integer, Boolean…
• Don’t allocate in onDraw
• Consider using Object Pools
Patterns to avoid memory churn
• SparseArray family to avoid
autoboxing
• Hundred of objects, not
thousands
• Use for with size and get
• Integer constants
• Unnecessary objects:
• Inmutable classes: String
• Autoboxing: Integer, Boolean…
• Foreach and iterators
• Enums
Patterns to use in critic areas of the app
inner loops animations custom views
• Handle Bitmaps in a proper way:
• Decode bitmaps to the desire size
• BitmapFactory.Options (inSampleSize, inDensity,
inTargetDensity)
• Load bitmaps in memory at the dimensions is going to be
displayed
• Don’t scale if you don’t need to (createScaledBitmap(btimap, int,
int).
• Use LRU cache.
Handling bitmaps
inSampleSize density
Performance is necessary for every app
“If we can write a map in a single line and you can put a value and get a
value, we don’t care how long it takes...”
Conference attendant at CppCon2014
“Ok, [...] people who don’t care about how long it takes is also the
reason why I’ve to wait 30 seconds for Word to boot up”
Mike Acton
Engine director at Insomniac Games
Tools, not rules
• Android Performance Case Study by @RomainGuy
• Performance Profiling Tools - https://developer.android.com/tools/
performance/index.html
• Android performance patterns videos by Colt McAnlis (@duhroach)
• Google + community: http://goo.gl/g7mxmI
References
@icemobile /company/icemobileicemobile.com/tech
Thank you!
Profiling tools and Android Performance patterns

Mais conteúdo relacionado

Mais procurados

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 

Mais procurados (20)

Flutter Intro
Flutter IntroFlutter Intro
Flutter Intro
 
Embedded Android : System Development - Part IV (Android System Services)
Embedded Android : System Development - Part IV (Android System Services)Embedded Android : System Development - Part IV (Android System Services)
Embedded Android : System Development - Part IV (Android System Services)
 
Jetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on AndroidJetpack Compose a new way to implement UI on Android
Jetpack Compose a new way to implement UI on Android
 
Android Navigation Component
Android Navigation ComponentAndroid Navigation Component
Android Navigation Component
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Flutter state management from zero to hero
Flutter state management from zero to heroFlutter state management from zero to hero
Flutter state management from zero to hero
 
Introduction to Qt programming
Introduction to Qt programmingIntroduction to Qt programming
Introduction to Qt programming
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical Presentation
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
코틀린 멀티플랫폼, 미지와의 조우
코틀린 멀티플랫폼, 미지와의 조우코틀린 멀티플랫폼, 미지와의 조우
코틀린 멀티플랫폼, 미지와의 조우
 
Python 게임서버 안녕하십니까 : RPC framework 편
Python 게임서버 안녕하십니까 : RPC framework 편Python 게임서버 안녕하십니까 : RPC framework 편
Python 게임서버 안녕하십니까 : RPC framework 편
 
Expressjs
ExpressjsExpressjs
Expressjs
 
Using the Splunk Java SDK
Using the Splunk Java SDKUsing the Splunk Java SDK
Using the Splunk Java SDK
 
Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016Optimizing the Graphics Pipeline with Compute, GDC 2016
Optimizing the Graphics Pipeline with Compute, GDC 2016
 
Reactjs
Reactjs Reactjs
Reactjs
 
Deep drive into rust programming language
Deep drive into rust programming languageDeep drive into rust programming language
Deep drive into rust programming language
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
 

Semelhante a Profiling tools and Android Performance patterns

Pref Presentation (2)
Pref Presentation (2)Pref Presentation (2)
Pref Presentation (2)
Prachi Patil
 
Beating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett DuncavageBeating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett Duncavage
Xamarin
 

Semelhante a Profiling tools and Android Performance patterns (20)

Android performance
Android performanceAndroid performance
Android performance
 
Coding Best Practices For Memory Management
Coding Best Practices For Memory Management Coding Best Practices For Memory Management
Coding Best Practices For Memory Management
 
The Good, the Bad and the Ugly things to do with android
The Good, the Bad and the Ugly things to do with androidThe Good, the Bad and the Ugly things to do with android
The Good, the Bad and the Ugly things to do with android
 
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
 
Сергей Жук "Android Performance Tips & Tricks"
Сергей Жук "Android Performance Tips & Tricks"Сергей Жук "Android Performance Tips & Tricks"
Сергей Жук "Android Performance Tips & Tricks"
 
Android Performance Tips & Tricks
Android Performance Tips & TricksAndroid Performance Tips & Tricks
Android Performance Tips & Tricks
 
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
 
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
 
Pref Presentation (2)
Pref Presentation (2)Pref Presentation (2)
Pref Presentation (2)
 
20 x Tips to better Optimize your Flash content
20 x Tips to better Optimize your Flash content20 x Tips to better Optimize your Flash content
20 x Tips to better Optimize your Flash content
 
0507 057 01 98 * Adana Cukurova Klima Servisleri
0507 057 01 98 * Adana Cukurova Klima Servisleri0507 057 01 98 * Adana Cukurova Klima Servisleri
0507 057 01 98 * Adana Cukurova Klima Servisleri
 
Optimizing mobile applications - Ian Dundore, Mark Harkness
Optimizing mobile applications - Ian Dundore, Mark HarknessOptimizing mobile applications - Ian Dundore, Mark Harkness
Optimizing mobile applications - Ian Dundore, Mark Harkness
 
Beating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett DuncavageBeating Android Fragmentation, Brett Duncavage
Beating Android Fragmentation, Brett Duncavage
 
Optimization in Unity: simple tips for developing with "no surprises" / Anton...
Optimization in Unity: simple tips for developing with "no surprises" / Anton...Optimization in Unity: simple tips for developing with "no surprises" / Anton...
Optimization in Unity: simple tips for developing with "no surprises" / Anton...
 
iOS App performance - Things to take care
iOS App performance - Things to take careiOS App performance - Things to take care
iOS App performance - Things to take care
 
Шлигін Олександр “Розробка ігор в Unity загальні помилки” GameDev Conference ...
Шлигін Олександр “Розробка ігор в Unity загальні помилки” GameDev Conference ...Шлигін Олександр “Розробка ігор в Unity загальні помилки” GameDev Conference ...
Шлигін Олександр “Розробка ігор в Unity загальні помилки” GameDev Conference ...
 
TU-Charts Project - First Spring
TU-Charts Project - First SpringTU-Charts Project - First Spring
TU-Charts Project - First Spring
 
TechGIG_Memory leaks in_java_webnair_26th_july_2012
TechGIG_Memory leaks in_java_webnair_26th_july_2012TechGIG_Memory leaks in_java_webnair_26th_july_2012
TechGIG_Memory leaks in_java_webnair_26th_july_2012
 
Memory Leaks in Android Applications
Memory Leaks in Android ApplicationsMemory Leaks in Android Applications
Memory Leaks in Android Applications
 
Android Effective UI: Tips, Tricks and Patterns
Android Effective UI: Tips, Tricks and PatternsAndroid Effective UI: Tips, Tricks and Patterns
Android Effective UI: Tips, Tricks and Patterns
 

Mais de icemobile

Mais de icemobile (20)

Design thinking for play meetup
Design thinking for play meetup Design thinking for play meetup
Design thinking for play meetup
 
Context chat UXcamp Amsterdam 2017
Context chat UXcamp Amsterdam 2017Context chat UXcamp Amsterdam 2017
Context chat UXcamp Amsterdam 2017
 
Analysing Memory Leaks
Analysing Memory LeaksAnalysing Memory Leaks
Analysing Memory Leaks
 
A date with data - CI’s Great British data visualisation adventure
A date with data - CI’s Great British data visualisation adventureA date with data - CI’s Great British data visualisation adventure
A date with data - CI’s Great British data visualisation adventure
 
Context Chat - why, what & how
Context Chat - why, what & howContext Chat - why, what & how
Context Chat - why, what & how
 
TAPOST Conference 2016 Riga // Better Products Faster: Let's bring the user i...
TAPOST Conference 2016 Riga // Better Products Faster: Let's bring the user i...TAPOST Conference 2016 Riga // Better Products Faster: Let's bring the user i...
TAPOST Conference 2016 Riga // Better Products Faster: Let's bring the user i...
 
Retail Loyalty Congress 2016 Masterclass IceMobile // Toronto Canada
Retail Loyalty Congress 2016 Masterclass IceMobile // Toronto CanadaRetail Loyalty Congress 2016 Masterclass IceMobile // Toronto Canada
Retail Loyalty Congress 2016 Masterclass IceMobile // Toronto Canada
 
Ladies that UX Amsterdam 18082016 - Experience Mapping with IceMobile
Ladies that UX Amsterdam 18082016 - Experience Mapping with IceMobile Ladies that UX Amsterdam 18082016 - Experience Mapping with IceMobile
Ladies that UX Amsterdam 18082016 - Experience Mapping with IceMobile
 
Service Discovery or Why each micro service should believe it's the only one ...
Service Discovery or Why each micro service should believe it's the only one ...Service Discovery or Why each micro service should believe it's the only one ...
Service Discovery or Why each micro service should believe it's the only one ...
 
Explorations in Cooperative Distributed Systems with Uber's Ringpop
Explorations in Cooperative Distributed Systems with Uber's RingpopExplorations in Cooperative Distributed Systems with Uber's Ringpop
Explorations in Cooperative Distributed Systems with Uber's Ringpop
 
About- Face: Reflections on Growing an Open-Source Mentality
About- Face: Reflections on Growing an Open-Source MentalityAbout- Face: Reflections on Growing an Open-Source Mentality
About- Face: Reflections on Growing an Open-Source Mentality
 
An Amsterdam perspective on Design Thinking
An Amsterdam perspective on Design ThinkingAn Amsterdam perspective on Design Thinking
An Amsterdam perspective on Design Thinking
 
Mobile App Europe 2015 Pulse UX Workshop Presentation
Mobile App Europe 2015 Pulse UX Workshop PresentationMobile App Europe 2015 Pulse UX Workshop Presentation
Mobile App Europe 2015 Pulse UX Workshop Presentation
 
Product Tank Amsterdam Pulse UX Presentation
Product Tank Amsterdam Pulse UX PresentationProduct Tank Amsterdam Pulse UX Presentation
Product Tank Amsterdam Pulse UX Presentation
 
AMS Node Meetup February presentation Jasper Spoel
AMS Node Meetup February presentation Jasper SpoelAMS Node Meetup February presentation Jasper Spoel
AMS Node Meetup February presentation Jasper Spoel
 
AMS Node Meetup, Node Summit 2015 Recap
AMS Node Meetup, Node Summit 2015 RecapAMS Node Meetup, Node Summit 2015 Recap
AMS Node Meetup, Node Summit 2015 Recap
 
AMS Node Meetup December presentation Phusion Passenger
AMS Node Meetup December presentation Phusion PassengerAMS Node Meetup December presentation Phusion Passenger
AMS Node Meetup December presentation Phusion Passenger
 
Design Thinking to accelerate Innovation - Masterclass on RLC2015 Barcelona
Design Thinking to accelerate Innovation - Masterclass on RLC2015 BarcelonaDesign Thinking to accelerate Innovation - Masterclass on RLC2015 Barcelona
Design Thinking to accelerate Innovation - Masterclass on RLC2015 Barcelona
 
The Numbers Magic (Amsterdam Node Meetup Presentation)
The Numbers Magic (Amsterdam Node Meetup Presentation)The Numbers Magic (Amsterdam Node Meetup Presentation)
The Numbers Magic (Amsterdam Node Meetup Presentation)
 
ProductTank Amsterdam - IceMobile Karlijn van den Berg
ProductTank Amsterdam - IceMobile Karlijn van den BergProductTank Amsterdam - IceMobile Karlijn van den Berg
ProductTank Amsterdam - IceMobile Karlijn van den Berg
 

Último

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 

Profiling tools and Android Performance patterns

  • 1. Profiling tools and Android performance patterns Providing a good user experience
  • 2. The mobile agency for food retail
  • 4. “Mobile internet will become the most important medium in people's lives.” Founded in 2002
  • 5. • Adding emotion to transactional loyalty • 120 developers, designers & specialists, HQ in Amsterdam, NL • Operating in 3 continents: Europe, North America and Asia The magic happens at the intersection IceMobile Creativity Technology
  • 6. Performance is about user experience Apps nowadays are all about fancy animations, complex transitions and custom views And the experience must be the most robust and similar as possible in any device
  • 8. GPU profiling Understanding the rendering pipeline
  • 9. Our apps must run at 60 frames per second ———— 1000ms 60 frames = 16,66ms per frame In this 16,66 ms we have to: • Do any computation • Update our screen to the GPU • Draw the screen • Deal with GC events
  • 10. Settings Developer options Profile GPU rendering Show on bars • Green: 16ms barrier • Blue: create and update the views display list • Purple (4.0+): time transferring resources to rendering thread • Red: android 2d renderer in OpenGL • Orange: CPU’s waiting time Profiling GPU rendering 16ms
  • 11. A lot of frame drops? Check for: • Unnecessary invalidations that may trigger a cascade of invalidations. (GPU View Updates can help profiling) • RelativeLayouts in a high hierarchy level • Nested weights in LinearLayouts • Unnecessary overdraw • Customs views not properly made Patterns to avoid bad performance
  • 12. • Use <merge> as root in your layout • Avoid unnecessary layouts • Don’t make allocations or heavy operations in OnDraw • Remove unnecessary calls to invalidate() • Consider creating your own ViewGroup invalidate() hierarchy invalidations onDraw() Patterns for custom views Make them as simple as possible OnMeasure/OnLayout…
  • 13. • True color: No overdraw • Blue: Overdrawn once • Green: Overdrawn twice • Pink: Overdrawn three times • Red: Overdrawn four times Profiling GPU overdraw
  • 14. • Depends on the GPU architecture: Nvidia’s Tegra is different than ImaginationTech’s SGX and so on. • Hierarchy Viewer (ViewServer by @RomainGuy for any phone) and Tracer Steps to follow when you have too much overdraw: • Simplify your drawables • Use 9patch with transparent parts • Caution with setting alpha in your views About overdraw
  • 16. Displays: • Free and allocated memory in real time • GC events Allows us: • Cause GC events • Start the allocation tracker • Dump the Java Heap Memory monitor
  • 17. • If our app is using an excessive amount of memory • When your app is running out of memory • If a GC event occurs and the memory is not properly free • If the app is slow due to a vast amount of GC events, a GC cascade What the memory monitor can tell us Runtime totalMemory() maxMemory() current heap size (bytes) max heap size (bytes)
  • 18. Heap dump We can use the heap dump to check: • The current memory state for our app • The amount of objects • Type of those objects • Hierarchy between references
  • 19. Allocation Tracker Allocation tracker displays: • Which classes and methods are allocating which objects • It’s possible to see allocated memory in each thread of your app
  • 21. Using our profiling tools in Android Studio: 1. Open memory monitor before opening an activity 2. Start the allocation tracker and dump the heap after loading the activity 3. Go to a different activity and force a GC event 4. Stop allocation tracker, dump the heap...and investigate Discovering memory leaks Allocation space in the HEAP * The allocation space is different between Dalvik andART Allocation space in the HEAP GC EVENT Leaked Memory Leaked Memory Allocated Memory Allocated Memory Needed Memory Needed Memory OUT OF MEMORY ERROR
  • 22. Don’t leak contexts in inner classes. Don’t leak views inside an activity. Don’t use WeakHashMap as cache. Only the keys are weak references. Use the proper context. AppContext != View context Use static classes instead of Inner classes. Use WeakReference or SoftReference. Release callbacks in a proper way (handlers, observers...) Avoiding memory leaks
  • 23. The principal cause of GC cascades is memory churn: high number of objects get allocated and potentially free in a short period of time. GC cascades: discovering and avoiding memory churn 16ms 16ms 16ms 16ms GCUPDATE GCUPDATE UP D Frame drop GC ATE draw draw draw
  • 24. • Don’t allocate a large amount of unnecessary objects • Immutable classes: String • Autoboxing: Integer, Boolean… • Don’t allocate in onDraw • Consider using Object Pools Patterns to avoid memory churn
  • 25. • SparseArray family to avoid autoboxing • Hundred of objects, not thousands • Use for with size and get • Integer constants • Unnecessary objects: • Inmutable classes: String • Autoboxing: Integer, Boolean… • Foreach and iterators • Enums Patterns to use in critic areas of the app inner loops animations custom views
  • 26. • Handle Bitmaps in a proper way: • Decode bitmaps to the desire size • BitmapFactory.Options (inSampleSize, inDensity, inTargetDensity) • Load bitmaps in memory at the dimensions is going to be displayed • Don’t scale if you don’t need to (createScaledBitmap(btimap, int, int). • Use LRU cache. Handling bitmaps inSampleSize density
  • 27. Performance is necessary for every app “If we can write a map in a single line and you can put a value and get a value, we don’t care how long it takes...” Conference attendant at CppCon2014 “Ok, [...] people who don’t care about how long it takes is also the reason why I’ve to wait 30 seconds for Word to boot up” Mike Acton Engine director at Insomniac Games
  • 29. • Android Performance Case Study by @RomainGuy • Performance Profiling Tools - https://developer.android.com/tools/ performance/index.html • Android performance patterns videos by Colt McAnlis (@duhroach) • Google + community: http://goo.gl/g7mxmI References