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