SlideShare ist ein Scribd-Unternehmen logo
1 von 36
1
Application
performance in
Android
Anand Hariharan
Clarice Technologies
2
How to achieve the best performance for
your applications on the android platform.
Anand Hariharan
Sr. Prod. Dev. Manager
for Tap 'n Tap at Clarice Technologies
3
About
• Joined Clarice in Sept 2009 to work on an android based
tablet-pc software platform (Tap 'n Tap).
• Worked on Enterprise software development with
Symantec/Veritas prior to Clarice.
• Experience in developing User Interfaces, enterprise and
high availability software.
• Keen interest in the mobile and RIA domain.
• Clarice is an offshore product development company.
• Setup in 2008 by Symantec Alumnus.
• Strong focus on user interface development and user centric
design.
• Excellent expertise in mobile domain with customers like
Nokia, Admaxim, Tap 'n Tap.
4
Topics
• Design for performance
o Understand the user
o Use recommended practices
o Pay attention to architecture
• Optimizing android applications
o Writing efficient code.
o Java tips to improve runtime performance.
o Avoiding ANRs.
o Best practices for performance.
o Tools to help improve performance.
• Q&A
5
Design for performance
Make it work, Make it right, Make it fast
- attributed to Kent Beck of TDD/Extreme programming fame
Should i be thinking about performance in the design phase ?
Make it right for the user.
Make it fast only after you measure.
Do think about performance from an architectural standpoint.
6
Design for performance
• Before making it work, ask questions about the application:
o How will it be used ? (Define use-cases)
o How much data is to be displayed and how ?
o Is there going to be a need for a scalable server side
component ?
o How will i manage user-perception during network or I/O
activity.
o How will my application co-exist with other applications
on the device ?
o How will my application affect battery-life and other
shared resources.
o How much memory will my application use, and how can i
minimize memory usage ?
7
Design for performance
Understand the user
• What features are the bare necessity, without which the
user may feel cheated ?
o List out these features, using your head, not your heart.
e.g. copy-paste and IPhone 1.0
• Should i prioritize some features over others ? And how is
this relevant to performance ?
o Choose robustness and user-friendliness to features that
can be postponed.
o Being responsive to the user is relevant to performance.
8
Design for performance
Understand the user
• What feature(s) are likely to cause frustration and
dissatisfaction ?
o Performance does not only mean speed. Its also about
managing user perception of the application. Some
techniques to improve user perception:
 Cancel-able progress indication for long running tasks.
 Responsiveness of the application.
 Playing nice with other applications.
 Frugal battery usage.
o e.g. Load time bitmaps.
9
Design for performance
Use recommended practices:
• SDKs will recommend best practices.
Follow these practices to play nice with other
applications.
• e.g. Android OS recommends using services for
background long-term processing. Coding this in
an activity may cause unnecessary load on the
system.
• Example : Service vs Activity for a short periodic
check for updates.
10
Design for performance
Pay attention to architecture:
Communication
• Chattiness, Inappropriate wire formats, large 
volumes of data over limited bandwidth networks. 
Avoid design decisions that limit 
performance
• Wire-level protocols.
• Persistence formats.
11
Optimizing Android 
applications for performance
We should forget about small efficiencies, say about 97% of 
the time: premature optimization is the root of all evil.
—Donald E. Knuth
12
Optimizing android apps
From developer.android.com:
2 mantras for writing efficient code.
• Don't do work that you dont need to.
• Don't allocate memory if you can avoid it.
To this, ill add:
2 mantras for optimizing code.
• Dont optimize unless you need to.
• Measure all optimizations before and after.
13
Optimizing android apps
Tips from d.android.com
• Avoid creation of objects
o Small objects created in a user interface loop will force a 
periodic GC, causing the app to stall momentarily.
o To extract individual strings from some input data (such 
as while parsing), try returning a "substring" instead. This 
causes the creation of a new String() object but shares 
the underlying char[] data with the input string.
o As far as possible, try not to return a String object from a 
function if the same effect can be achieved by passing in 
a StringBuffer to the function.
14
Optimizing android apps
Tips from d.android.com
• For primitive type arrays, use a set of 1-dimensional arrays 
instead of 2 dimensional arrays. For e.g. 
o char dimarr [2][10], can be represented as char dim1 [10], 
char dim2[10]; This is much faster than a 2 dimensional 
array.
•  If a function does not need to access member variables, 
make it static. Static functions are invoked 15-20% faster 
than virtual methods.
• Avoid use of getter function from code within the class. local 
fields are accessed much faster than a trivial getter function. 
With JIT, this distinction might go away in the future, but this 
optimization is still good if you are targeting Froyo (2.2).
15
The ANR dialog
• Applications that are not 
"responsive" will be prone to 
ANR dialogs.
• The android OS will display an 
ANR if:
o The application can not 
respond to user input for 
more than 5 seconds.
o A BroadcastReceiver  hasnt 
finished execution within 10 
seconds.
• ANR is a definite indication of 
too much work being done on 
the main thread of the 
application.
16
Avoiding the ANR dialog
• Get off the main thread !
o Android apps are single threaded. All input processing 
takes place on the main thread.
o Do all time consuming processing in a child thread. 
o Go asynchronous !
 Spawn a new thread for most I/O, network or 
database access.
o Do as little as possible on life-cycle methods such as 
onCreate and onResume.
o Never call Thread.sleep() or Thread.wait() on the main 
thread.
17
Avoiding the ANR dialog
• Keep the processing done within a BroadcastReceiver to a 
minimum.
• To spawn a long running process from the receiver, start a 
service.
• Never start an activity from a BroadcastReceiver, instead 
display a notification which will start the activity when 
clicked. 
Starting an activity can surprise users leading to poor 
perceived performance.
18
Best practices for performance
• Dont overload a single activity
o An activity is a transient view into your 
application.
o Overloading an activity presents many problems 
such as
Slow loading time.
Unnecessary layouts and resources that load 
during launch.
Slower transitions between applications on 
device due to larger onResume() processing.
Clunkiness
e.g  Settings activity and main activity
19
Best practices for performance
• Keep your activity small
o Optimize images
 Reducing color depth of images makes the final app
much smaller and will also use less memory overall.
A decent choice is to go for 16-bit colour if possible.
o Optimize layouts
 Reduce the number of views
 Avoid nesting of views.
 Try to use the minimum number of views as possible.
 Use hierarchyviewer to determine unnecessary levels
in layouts.
20
Best practices for performance
• Track memory allocations
o Use debugging tools to identify and track memory
allocations. (Allocation tracker DDMS).
o Remember, try not to allocate memory if possible.
o Be aware of ways memory leaks can creep into code.
Specifically avoid passing the Activity Context object to
long lived widgets. Instead use the Application Context.
• Consider custom views over view hierarchies for interactive
views rather than using standard widgets
o Custom views can improve performance significantly due
to less layout related overhead.
o Consider custom views after carefully studying the
problem at hand.
21
Best practices for performance
• As far as possible, let android handle orientation changes.
o Pass around any data that is expensive to load (e.g.
Images from an network source) across orientation
changes using the onRetainNonConfigurationInstance()
method. This will improve the load time of the new activity
and will lead to fast orientation changes.
• Use SoftReferences for cached data.
o Doing so will allow the garbage collector to free memory
faster, resulting in better performance for the device.
o The GC claims objects which are wrapped by a
SoftReference first.
22
Best practices for performance
• If possible, avoid frequent writes to db/storage
o Writes to flash storage are slow
o Can take anywhere between 5-200ms on different
devices.
o Write performance degrades consistently with more data
on the SDCard.
o Be cognizant of how much writing the application does
and how frequently. SQLite database can be pretty heavy
on writes.
• Consider a pool of small objects if your application needs it.
o Most game creators need a large number or small
objects. A pool of these objects that can be reused will
improve performance by not allowing the GC to kick in
more often.
23
Best practices for performance
• Avoid using data from multiple tables in an AdapterView
o ListAdapter for example will slow down tremendously if
there is data being read from multiple tables to render a
single list item.
o If needed add columns to the table with the data to be
presented and then serve the data using a view or
projection.
• Measure, Measure, Measure.
o It is very important to measure performance before doing
anything about it.
o Optimize Judiciously.
24
Tools to help optimize android apps
layoutopt
• Tool available with the SDK to point out some obvious
problems with layouts.
o Helps you tune your layout to acheive better performance.
o Some problems that it points out:
 If layout has a top level FrameLayout, it will suggest
usage of the <merge> tag to avoid one level in the view
heirarchy.
 Points out when layout is too deep (10 levels)
 Points out when layout has too many views (80)
 Suggests replacement for widgets and best practices for
layout files.
25
Tools to help optimize android apps
layoutopt : Sample output
custom_cat_list_item.xml
6:28 This tag and its children can be replaced by one <TextView/> and a compound
drawable
18:19 Use an android:layout_width of 0dip instead of wrap_content for better
performance
news_portlet_small.xml
53:70 This tag and its children can be replaced by one <TextView/> and a
compound drawable
60:60 Use an android:layout_width of 0dip instead of wrap_content for better
performance
news_item_view.xml
59:77 This LinearLayout layout or its RelativeLayout parent is useless
news.xml
-1:-1 This layout has too many views: 93 views, it should have <= 80!
174:189 Use an android:layout_width of 0dip instead of wrap_content for better
performance
26
Tools to help optimize android apps
hierarchyviewer
• Generally used for viewing layout hierarchies and tuning
parameters of views.
• Provides a visual representation of your view hierarchy
which is valuable in debugging nesting in your layouts.
• Analyze the tree structure to get insights on how choosing a
different layout may solve nesting issues.
• Used in conjunction with layoutopt, hierarchyviewer is
powerful tool to help optimize your layouts.
• Most useful feature for performance is the ability to call
invalidate or requestLayout for individual views. Ends up
calling "onMeasure" and adjusts the view hierarchy. Used in
conjunction with the debugger, this can be very handy to debug
performance issues in custom views.
27
hierarchyviewer
28
Tools to help optimize android apps
Allocation tracker
• Excellent tool to trace where memory is allocated.
• Gives you insight on what code to target first to reduce
memory footprint.
• Pay special attention to functions that return small new
objects and are called very frequently.
• Available with the DDMS tool which ships with the SDK.
• To use, simply run your app, start tracking before you
perform an operation you want to test. The tool will show
you all allocations that happened during that action.
• Optimizing frequent allocations in critical paths can make a
tremendous difference in apps like games.
29
Allocation Tracker
30
Tools to help optimize android apps
traceview
• An excellent tool for identifying performance bottlenecks.
• 4 steps to tracing app performance
o Insert Debug.startMethodTracing() and
Debug.stopMethodTracing() calls in code.
 Tip: To trace the full activity, call start in onStart() and
stop in onStop().
o Compile and run the app. Exercise the parts that seem
obviously slow.
o Stop the app and download the tracefile.
o Run traceview with the tracefile.
31
Traceview
traceview
• Tip: Never fail to trace custom adapters. Be suspicious of
anything that has a "getView()" call.
Sample trace
32
Tools to help optimize android apps
traceview
Some tips to use the traceview information
• #0 : Only target items that stand out in the trace.
• #1 Pay attention to the % exclusive time spent in the
method. Target the calls with greatest time to optimize the
code within the method.
• #2 Pay attention to the number of calls to a function. There
may be gains in targeting methods with large number or
calls by:
o Making that method static if possible.
o Try to remove a method call by inlining the code explicitly.
33
Tools to help optimize android apps
zipalign
• An optimization tool available with the SDK.
• Aligns resources on 4-byte boundaries.
• Zipalined apks load resources significantly faster.
• Unaligned apks end up running slower and using more
memory than aligned ones.
• Dont forget to align your applications before uploading them
to the market.
34
A story about optimization
The practice of Programming - Brian Kernighan
This program was "too slow". The team decided to profile and
optimize. After some serious profiling, they found a single function
that was using about 40% of CPU time. Huge.
The team got to work optimizing this function. They found it was not
particularly efficient. They worked hard and long to optimize this
function, knowing that every bit of speed they could wring out of
this one routine would pay off handsomely.
When they had worked it as far as they could, they stepped back to
test. The system did not run any faster. After days of optimizing
code, finally someone realized that this routine they were
optimizing was....the idle loop.
35
Moral of the optimization story
• UNDERSTAND WHAT YOU ARE OPTIMIZING.
• Leave it alone until you know its a problem
• Measure, Measure, Measure
• Use tools to profile and gain experience to cut out the noise
in the output.
• Make an optimization pass part of your development cycle.
• Dont target micro-optimizations unless warranted. Even
then, do it *after* you find the maximum gain looking at the
macro level.
• Dont write unreadable code in the name of performance.
36
THANK YOU

Weitere ähnliche Inhalte

Andere mochten auch

Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices
Amgad Muhammad
 

Andere mochten auch (6)

Power optimization for Android apps
Power optimization for Android appsPower optimization for Android apps
Power optimization for Android apps
 
Detect all memory leaks with LeakCanary!
 Detect all memory leaks with LeakCanary! Detect all memory leaks with LeakCanary!
Detect all memory leaks with LeakCanary!
 
LCA13: Memory Hotplug on Android
LCA13: Memory Hotplug on AndroidLCA13: Memory Hotplug on Android
LCA13: Memory Hotplug on Android
 
Android Performance Best Practices
Android Performance Best Practices Android Performance Best Practices
Android Performance Best Practices
 
AndroidLint #DroidKaigi
AndroidLint #DroidKaigiAndroidLint #DroidKaigi
AndroidLint #DroidKaigi
 
Android lint-srp-practice
Android lint-srp-practiceAndroid lint-srp-practice
Android lint-srp-practice
 

Ähnlich wie Performance in Android: Tips and Techniques [IndicThreads Mobile Application Development Conference]

Guidelines for Android application design.pptx
Guidelines for Android application design.pptxGuidelines for Android application design.pptx
Guidelines for Android application design.pptx
debasish duarah
 
Notes from Educator Pre-training Briefing 1 - Summary of AfG-toolset 2012-13
Notes from Educator Pre-training Briefing 1  - Summary of AfG-toolset 2012-13Notes from Educator Pre-training Briefing 1  - Summary of AfG-toolset 2012-13
Notes from Educator Pre-training Briefing 1 - Summary of AfG-toolset 2012-13
CDI Apps for Good
 
Mobile Project Management
Mobile Project ManagementMobile Project Management
Mobile Project Management
Lee Schlenker
 
Property dealing , A .net project
Property dealing , A .net projectProperty dealing , A .net project
Property dealing , A .net project
Anjali Kamboj
 

Ähnlich wie Performance in Android: Tips and Techniques [IndicThreads Mobile Application Development Conference] (20)

Sidiq Permana - Building For The Next Billion Users
Sidiq Permana - Building For The Next Billion UsersSidiq Permana - Building For The Next Billion Users
Sidiq Permana - Building For The Next Billion Users
 
[TTT Meetup] Enhance mobile app testing with performance-centric strategies (...
[TTT Meetup] Enhance mobile app testing with performance-centric strategies (...[TTT Meetup] Enhance mobile app testing with performance-centric strategies (...
[TTT Meetup] Enhance mobile app testing with performance-centric strategies (...
 
android development training in mumbai
android development training in mumbaiandroid development training in mumbai
android development training in mumbai
 
Going native - Taking desktop applications to mobile devices
Going native - Taking desktop applications to mobile devicesGoing native - Taking desktop applications to mobile devices
Going native - Taking desktop applications to mobile devices
 
OOSE UNIT-1.pdf
OOSE UNIT-1.pdfOOSE UNIT-1.pdf
OOSE UNIT-1.pdf
 
2015 Mastering SAP Tech - Enterprise Mobility - Testing Lessons Learned
2015 Mastering SAP Tech - Enterprise Mobility - Testing Lessons Learned2015 Mastering SAP Tech - Enterprise Mobility - Testing Lessons Learned
2015 Mastering SAP Tech - Enterprise Mobility - Testing Lessons Learned
 
Evolving to Cloud-Native - Anand Rao
Evolving to Cloud-Native - Anand RaoEvolving to Cloud-Native - Anand Rao
Evolving to Cloud-Native - Anand Rao
 
Build A Scalable Mobile App
Build A Scalable Mobile App Build A Scalable Mobile App
Build A Scalable Mobile App
 
Guidelines for Android application design.pptx
Guidelines for Android application design.pptxGuidelines for Android application design.pptx
Guidelines for Android application design.pptx
 
SenchaCon 2016: Using Ext JS 6 for Cross-Platform Development on Mobile - And...
SenchaCon 2016: Using Ext JS 6 for Cross-Platform Development on Mobile - And...SenchaCon 2016: Using Ext JS 6 for Cross-Platform Development on Mobile - And...
SenchaCon 2016: Using Ext JS 6 for Cross-Platform Development on Mobile - And...
 
How to Decide Technology Stack for Your Next Software Development Project?
How to Decide Technology Stack for Your Next Software Development Project?How to Decide Technology Stack for Your Next Software Development Project?
How to Decide Technology Stack for Your Next Software Development Project?
 
Develop, deploy, and operate services at reddit scale oscon 2018
Develop, deploy, and operate services at reddit scale   oscon 2018Develop, deploy, and operate services at reddit scale   oscon 2018
Develop, deploy, and operate services at reddit scale oscon 2018
 
Embedded Systems.pdf
Embedded Systems.pdfEmbedded Systems.pdf
Embedded Systems.pdf
 
Notes from Educator Pre-training Briefing 1 - Summary of AfG-toolset 2012-13
Notes from Educator Pre-training Briefing 1  - Summary of AfG-toolset 2012-13Notes from Educator Pre-training Briefing 1  - Summary of AfG-toolset 2012-13
Notes from Educator Pre-training Briefing 1 - Summary of AfG-toolset 2012-13
 
Mobile Project Management
Mobile Project ManagementMobile Project Management
Mobile Project Management
 
Designing Mobile Apps for the Enterprise
Designing Mobile Apps for the EnterpriseDesigning Mobile Apps for the Enterprise
Designing Mobile Apps for the Enterprise
 
Building LLM Solutions using Open Source and Closed Source Solutions in Coher...
Building LLM Solutions using Open Source and Closed Source Solutions in Coher...Building LLM Solutions using Open Source and Closed Source Solutions in Coher...
Building LLM Solutions using Open Source and Closed Source Solutions in Coher...
 
Enterprise Frameworks: Java & .NET
Enterprise Frameworks: Java & .NETEnterprise Frameworks: Java & .NET
Enterprise Frameworks: Java & .NET
 
Property dealing , A .net project
Property dealing , A .net projectProperty dealing , A .net project
Property dealing , A .net project
 
Overview of Software Engineering Principles - SCPS311.pptx
Overview of Software Engineering Principles - SCPS311.pptxOverview of Software Engineering Principles - SCPS311.pptx
Overview of Software Engineering Principles - SCPS311.pptx
 

Mehr von IndicThreads

Scrap Your MapReduce - Apache Spark
 Scrap Your MapReduce - Apache Spark Scrap Your MapReduce - Apache Spark
Scrap Your MapReduce - Apache Spark
IndicThreads
 
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
IndicThreads
 
Unraveling OpenStack Clouds
 Unraveling OpenStack Clouds Unraveling OpenStack Clouds
Unraveling OpenStack Clouds
IndicThreads
 

Mehr von IndicThreads (20)

Http2 is here! And why the web needs it
Http2 is here! And why the web needs itHttp2 is here! And why the web needs it
Http2 is here! And why the web needs it
 
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsUnderstanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
 
Go Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayGo Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang way
 
Building Resilient Microservices
Building Resilient Microservices Building Resilient Microservices
Building Resilient Microservices
 
App using golang indicthreads
App using golang  indicthreadsApp using golang  indicthreads
App using golang indicthreads
 
Building on quicksand microservices indicthreads
Building on quicksand microservices  indicthreadsBuilding on quicksand microservices  indicthreads
Building on quicksand microservices indicthreads
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
 
Iot secure connected devices indicthreads
Iot secure connected devices indicthreadsIot secure connected devices indicthreads
Iot secure connected devices indicthreads
 
Real world IoT for enterprises
Real world IoT for enterprisesReal world IoT for enterprises
Real world IoT for enterprises
 
IoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreads
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
Building & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameBuilding & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fame
 
Internet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceInternet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads Conference
 
Cars and Computers: Building a Java Carputer
 Cars and Computers: Building a Java Carputer Cars and Computers: Building a Java Carputer
Cars and Computers: Building a Java Carputer
 
Scrap Your MapReduce - Apache Spark
 Scrap Your MapReduce - Apache Spark Scrap Your MapReduce - Apache Spark
Scrap Your MapReduce - Apache Spark
 
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 
Speed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackSpeed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedback
 
Unraveling OpenStack Clouds
 Unraveling OpenStack Clouds Unraveling OpenStack Clouds
Unraveling OpenStack Clouds
 
Digital Transformation of the Enterprise. What IT leaders need to know!
Digital Transformation of the Enterprise. What IT  leaders need to know!Digital Transformation of the Enterprise. What IT  leaders need to know!
Digital Transformation of the Enterprise. What IT leaders need to know!
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Performance in Android: Tips and Techniques [IndicThreads Mobile Application Development Conference]

  • 2. 2 How to achieve the best performance for your applications on the android platform. Anand Hariharan Sr. Prod. Dev. Manager for Tap 'n Tap at Clarice Technologies
  • 3. 3 About • Joined Clarice in Sept 2009 to work on an android based tablet-pc software platform (Tap 'n Tap). • Worked on Enterprise software development with Symantec/Veritas prior to Clarice. • Experience in developing User Interfaces, enterprise and high availability software. • Keen interest in the mobile and RIA domain. • Clarice is an offshore product development company. • Setup in 2008 by Symantec Alumnus. • Strong focus on user interface development and user centric design. • Excellent expertise in mobile domain with customers like Nokia, Admaxim, Tap 'n Tap.
  • 4. 4 Topics • Design for performance o Understand the user o Use recommended practices o Pay attention to architecture • Optimizing android applications o Writing efficient code. o Java tips to improve runtime performance. o Avoiding ANRs. o Best practices for performance. o Tools to help improve performance. • Q&A
  • 5. 5 Design for performance Make it work, Make it right, Make it fast - attributed to Kent Beck of TDD/Extreme programming fame Should i be thinking about performance in the design phase ? Make it right for the user. Make it fast only after you measure. Do think about performance from an architectural standpoint.
  • 6. 6 Design for performance • Before making it work, ask questions about the application: o How will it be used ? (Define use-cases) o How much data is to be displayed and how ? o Is there going to be a need for a scalable server side component ? o How will i manage user-perception during network or I/O activity. o How will my application co-exist with other applications on the device ? o How will my application affect battery-life and other shared resources. o How much memory will my application use, and how can i minimize memory usage ?
  • 7. 7 Design for performance Understand the user • What features are the bare necessity, without which the user may feel cheated ? o List out these features, using your head, not your heart. e.g. copy-paste and IPhone 1.0 • Should i prioritize some features over others ? And how is this relevant to performance ? o Choose robustness and user-friendliness to features that can be postponed. o Being responsive to the user is relevant to performance.
  • 8. 8 Design for performance Understand the user • What feature(s) are likely to cause frustration and dissatisfaction ? o Performance does not only mean speed. Its also about managing user perception of the application. Some techniques to improve user perception:  Cancel-able progress indication for long running tasks.  Responsiveness of the application.  Playing nice with other applications.  Frugal battery usage. o e.g. Load time bitmaps.
  • 9. 9 Design for performance Use recommended practices: • SDKs will recommend best practices. Follow these practices to play nice with other applications. • e.g. Android OS recommends using services for background long-term processing. Coding this in an activity may cause unnecessary load on the system. • Example : Service vs Activity for a short periodic check for updates.
  • 13. 13 Optimizing android apps Tips from d.android.com • Avoid creation of objects o Small objects created in a user interface loop will force a  periodic GC, causing the app to stall momentarily. o To extract individual strings from some input data (such  as while parsing), try returning a "substring" instead. This  causes the creation of a new String() object but shares  the underlying char[] data with the input string. o As far as possible, try not to return a String object from a  function if the same effect can be achieved by passing in  a StringBuffer to the function.
  • 14. 14 Optimizing android apps Tips from d.android.com • For primitive type arrays, use a set of 1-dimensional arrays  instead of 2 dimensional arrays. For e.g.  o char dimarr [2][10], can be represented as char dim1 [10],  char dim2[10]; This is much faster than a 2 dimensional  array. •  If a function does not need to access member variables,  make it static. Static functions are invoked 15-20% faster  than virtual methods. • Avoid use of getter function from code within the class. local  fields are accessed much faster than a trivial getter function.  With JIT, this distinction might go away in the future, but this  optimization is still good if you are targeting Froyo (2.2).
  • 15. 15 The ANR dialog • Applications that are not  "responsive" will be prone to  ANR dialogs. • The android OS will display an  ANR if: o The application can not  respond to user input for  more than 5 seconds. o A BroadcastReceiver  hasnt  finished execution within 10  seconds. • ANR is a definite indication of  too much work being done on  the main thread of the  application.
  • 16. 16 Avoiding the ANR dialog • Get off the main thread ! o Android apps are single threaded. All input processing  takes place on the main thread. o Do all time consuming processing in a child thread.  o Go asynchronous !  Spawn a new thread for most I/O, network or  database access. o Do as little as possible on life-cycle methods such as  onCreate and onResume. o Never call Thread.sleep() or Thread.wait() on the main  thread.
  • 17. 17 Avoiding the ANR dialog • Keep the processing done within a BroadcastReceiver to a  minimum. • To spawn a long running process from the receiver, start a  service. • Never start an activity from a BroadcastReceiver, instead  display a notification which will start the activity when  clicked.  Starting an activity can surprise users leading to poor  perceived performance.
  • 18. 18 Best practices for performance • Dont overload a single activity o An activity is a transient view into your  application. o Overloading an activity presents many problems  such as Slow loading time. Unnecessary layouts and resources that load  during launch. Slower transitions between applications on  device due to larger onResume() processing. Clunkiness e.g  Settings activity and main activity
  • 19. 19 Best practices for performance • Keep your activity small o Optimize images  Reducing color depth of images makes the final app much smaller and will also use less memory overall. A decent choice is to go for 16-bit colour if possible. o Optimize layouts  Reduce the number of views  Avoid nesting of views.  Try to use the minimum number of views as possible.  Use hierarchyviewer to determine unnecessary levels in layouts.
  • 20. 20 Best practices for performance • Track memory allocations o Use debugging tools to identify and track memory allocations. (Allocation tracker DDMS). o Remember, try not to allocate memory if possible. o Be aware of ways memory leaks can creep into code. Specifically avoid passing the Activity Context object to long lived widgets. Instead use the Application Context. • Consider custom views over view hierarchies for interactive views rather than using standard widgets o Custom views can improve performance significantly due to less layout related overhead. o Consider custom views after carefully studying the problem at hand.
  • 21. 21 Best practices for performance • As far as possible, let android handle orientation changes. o Pass around any data that is expensive to load (e.g. Images from an network source) across orientation changes using the onRetainNonConfigurationInstance() method. This will improve the load time of the new activity and will lead to fast orientation changes. • Use SoftReferences for cached data. o Doing so will allow the garbage collector to free memory faster, resulting in better performance for the device. o The GC claims objects which are wrapped by a SoftReference first.
  • 22. 22 Best practices for performance • If possible, avoid frequent writes to db/storage o Writes to flash storage are slow o Can take anywhere between 5-200ms on different devices. o Write performance degrades consistently with more data on the SDCard. o Be cognizant of how much writing the application does and how frequently. SQLite database can be pretty heavy on writes. • Consider a pool of small objects if your application needs it. o Most game creators need a large number or small objects. A pool of these objects that can be reused will improve performance by not allowing the GC to kick in more often.
  • 23. 23 Best practices for performance • Avoid using data from multiple tables in an AdapterView o ListAdapter for example will slow down tremendously if there is data being read from multiple tables to render a single list item. o If needed add columns to the table with the data to be presented and then serve the data using a view or projection. • Measure, Measure, Measure. o It is very important to measure performance before doing anything about it. o Optimize Judiciously.
  • 24. 24 Tools to help optimize android apps layoutopt • Tool available with the SDK to point out some obvious problems with layouts. o Helps you tune your layout to acheive better performance. o Some problems that it points out:  If layout has a top level FrameLayout, it will suggest usage of the <merge> tag to avoid one level in the view heirarchy.  Points out when layout is too deep (10 levels)  Points out when layout has too many views (80)  Suggests replacement for widgets and best practices for layout files.
  • 25. 25 Tools to help optimize android apps layoutopt : Sample output custom_cat_list_item.xml 6:28 This tag and its children can be replaced by one <TextView/> and a compound drawable 18:19 Use an android:layout_width of 0dip instead of wrap_content for better performance news_portlet_small.xml 53:70 This tag and its children can be replaced by one <TextView/> and a compound drawable 60:60 Use an android:layout_width of 0dip instead of wrap_content for better performance news_item_view.xml 59:77 This LinearLayout layout or its RelativeLayout parent is useless news.xml -1:-1 This layout has too many views: 93 views, it should have <= 80! 174:189 Use an android:layout_width of 0dip instead of wrap_content for better performance
  • 26. 26 Tools to help optimize android apps hierarchyviewer • Generally used for viewing layout hierarchies and tuning parameters of views. • Provides a visual representation of your view hierarchy which is valuable in debugging nesting in your layouts. • Analyze the tree structure to get insights on how choosing a different layout may solve nesting issues. • Used in conjunction with layoutopt, hierarchyviewer is powerful tool to help optimize your layouts. • Most useful feature for performance is the ability to call invalidate or requestLayout for individual views. Ends up calling "onMeasure" and adjusts the view hierarchy. Used in conjunction with the debugger, this can be very handy to debug performance issues in custom views.
  • 28. 28 Tools to help optimize android apps Allocation tracker • Excellent tool to trace where memory is allocated. • Gives you insight on what code to target first to reduce memory footprint. • Pay special attention to functions that return small new objects and are called very frequently. • Available with the DDMS tool which ships with the SDK. • To use, simply run your app, start tracking before you perform an operation you want to test. The tool will show you all allocations that happened during that action. • Optimizing frequent allocations in critical paths can make a tremendous difference in apps like games.
  • 30. 30 Tools to help optimize android apps traceview • An excellent tool for identifying performance bottlenecks. • 4 steps to tracing app performance o Insert Debug.startMethodTracing() and Debug.stopMethodTracing() calls in code.  Tip: To trace the full activity, call start in onStart() and stop in onStop(). o Compile and run the app. Exercise the parts that seem obviously slow. o Stop the app and download the tracefile. o Run traceview with the tracefile.
  • 31. 31 Traceview traceview • Tip: Never fail to trace custom adapters. Be suspicious of anything that has a "getView()" call. Sample trace
  • 32. 32 Tools to help optimize android apps traceview Some tips to use the traceview information • #0 : Only target items that stand out in the trace. • #1 Pay attention to the % exclusive time spent in the method. Target the calls with greatest time to optimize the code within the method. • #2 Pay attention to the number of calls to a function. There may be gains in targeting methods with large number or calls by: o Making that method static if possible. o Try to remove a method call by inlining the code explicitly.
  • 33. 33 Tools to help optimize android apps zipalign • An optimization tool available with the SDK. • Aligns resources on 4-byte boundaries. • Zipalined apks load resources significantly faster. • Unaligned apks end up running slower and using more memory than aligned ones. • Dont forget to align your applications before uploading them to the market.
  • 34. 34 A story about optimization The practice of Programming - Brian Kernighan This program was "too slow". The team decided to profile and optimize. After some serious profiling, they found a single function that was using about 40% of CPU time. Huge. The team got to work optimizing this function. They found it was not particularly efficient. They worked hard and long to optimize this function, knowing that every bit of speed they could wring out of this one routine would pay off handsomely. When they had worked it as far as they could, they stepped back to test. The system did not run any faster. After days of optimizing code, finally someone realized that this routine they were optimizing was....the idle loop.
  • 35. 35 Moral of the optimization story • UNDERSTAND WHAT YOU ARE OPTIMIZING. • Leave it alone until you know its a problem • Measure, Measure, Measure • Use tools to profile and gain experience to cut out the noise in the output. • Make an optimization pass part of your development cycle. • Dont target micro-optimizations unless warranted. Even then, do it *after* you find the maximum gain looking at the macro level. • Dont write unreadable code in the name of performance.