performance in android: tips and techniques [indicthreads mobile application development conference]

36
1 Application performance in Android Anand Hariharan Clarice Technologies

Upload: indicthreads

Post on 07-Jul-2015

1.890 views

Category:

Technology


1 download

DESCRIPTION

Session Presented at 1st IndicThreads.com Conference On Mobile Application Development held on 19-20 November 2010 in Pune, India WEB: http://M10.IndicThreads.com ------------ Speaker: Anand Hariharan Abstract: While desktops and laptops have gotten more and more powerful, performance considerations for applications running on the desktop are not critical to the success of the app. However, mobile devices are quickly becoming a viable computing platform and many devices now can run various applications which were only seen on the desktop previously. As the developer community ports applications from desktop to the cell phone, performance becomes a very critical factor for success since cellphones are still under-powered as compared to the desktops. This presentation will talk about best practices w.r.t performance while developing applications for the Android Platform. It will outline tips and techniques for extracting the best performance from android. These tips and techniques are a collation of well known java best practices that apply to Android as well as our learning at TapNTap as we go about building a next generation user interface for an Internet tablet. Here are some of the topics that will be covered: Java performance tips that will enhance your android app performance. Performance Best practices which will apply even for non-android Java programming. Architecting to avoid the dreaded “ANR (Application not responding)” dialog. Benchmarking and tracing tools: Caliper Traceview Building custom views : Tips on how to extract the best frame rate before knocking on OpenGLs door. Precompute for performance. Layout tricks to get the best load performance. Differences between mobile and tablets. Takeaways for the Audience Best practices for Java development (performance improvement takeaways for any java app). Tips/tools and techniques on applying these best practices.

TRANSCRIPT

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

1

Application performance in

Android

Anand HariharanClarice Technologies

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

2

How to achieve the best performance for your applications on the android platform.

Anand HariharanSr. Prod. Dev. Manager

for Tap 'n Tap at Clarice Technologies

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

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.

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

4

Topics

• Design for performanceo Understand the usero Use recommended practiceso Pay attention to architecture

• Optimizing android applicationso 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

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

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.

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

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 ?

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

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.

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

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.

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

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.

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

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.

 

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

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

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

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.

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

13

Optimizing android appsTips from d.android.com

• Avoid creation of objectso 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.

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

14

Optimizing android appsTips 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).

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

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.

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

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.

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

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.

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

18

Best practices for performance• Dont overload a single activity

o An activity is a transient view into your application.

oOverloading an activity presents many problems such asSlow 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

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

19

Best practices for performance

• Keep your activity smallo 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 layoutsReduce the number of viewsAvoid nesting of views.Try to use the minimum number of views as possible.Use hierarchyviewer to determine unnecessary levels

in layouts.

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

20

Best practices for performance

• Track memory allocationso 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 widgetso Custom views can improve performance significantly due

to less layout related overhead.o Consider custom views after carefully studying the

problem at hand.

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

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.

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

22

Best practices for performance• If possible, avoid frequent writes to db/storage

o Writes to flash storage are slowo 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.

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

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.

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

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.

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

25

Tools to help optimize android apps

layoutopt : Sample output

custom_cat_list_item.xml6:28 This tag and its children can be replaced by one <TextView/> and a compound

drawable18:19 Use an android:layout_width of 0dip instead of wrap_content for better

performancenews_portlet_small.xml53:70 This tag and its children can be replaced by one <TextView/> and a

compound drawable60:60 Use an android:layout_width of 0dip instead of wrap_content for better

performancenews_item_view.xml59:77 This LinearLayout layout or its RelativeLayout parent is uselessnews.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

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

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.

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

27

hierarchyviewer

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

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.

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

29

Allocation Tracker

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

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.

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

31

Traceviewtraceview• Tip: Never fail to trace custom adapters. Be suspicious of

anything that has a "getView()" call.

Sample trace

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

32

Tools to help optimize android apps

traceviewSome 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.

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

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.

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

34

A story about optimizationThe 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.

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

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.

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

36

THANK YOU