This is a discussion on Android Tips and tricks within the Mobile Software Development forums, part of the Software Development category; Introduction There are two basic rules for resource-constrained systems: * Don't do work that you don't need to ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Introduction There are two basic rules for resource-constrained systems: * Don't do work that you don't need to do. * Don't allocate memory if you can avoid it. All the tips below follow from these two basic tenets. Some would argue that much of the advice on this page amounts to "premature optimization." While it's true that micro-optimizations sometimes make it harder to develop efficient data structures and algorithms, on embedded devices like handsets you often simply have no choice. For instance, if you bring your assumptions about VM performance on desktop machines to Android, you're quite likely to write code that exhausts system memory. This will bring your application to a crawl — let alone what it will do to other programs running on the system! That's why these guidelines are important. Android's success depends on the user experience that your applications provide, and that user experience depends in part on whether your code is responsive and snappy, or slow and aggravating. Since all our applications will run on the same devices, we're all in this together, in a way. Think of this document as like the rules of the road you had to learn when you got your driver's license: things run smoothly when everybody follows them, but when you don't, you get your car smashed up. Before we get down to brass tacks, a brief observation: nearly all issues described below are valid whether or not the VM features a JIT compiler. If I have two methods that accomplish the same thing, and the interpreted execution of foo() is faster than bar(), then the compiled version of foo() will probably be as fast or faster than compiled bar(). It is unwise to rely on a compiler to "save" you and make your code fast enough
__________________ cheers Aman |
| Sponsored Links |
| |||
| Avoid Creating Objects Object creation is never free. A generational GC with per-thread allocation pools for temporary objects can make allocation cheaper, but allocating memory is always more expensive than not allocating memory. If you allocate objects in a user interface loop, you will force a periodic garbage collection, creating little "hiccups" in the user experience. Thus, you should avoid creating object instances you don't need to. Some examples of things that can help: * When extracting strings from a set of input data, try to return a substring of the original data, instead of creating a copy. You will create a new String object, but it will share the char[] with the data. * If you have a method returning a string, and you know that its result will always be appended to a StringBuffer anyway, change your signature and implementation so that the function does the append directly, instead of creating a short-lived temporary object. A somewhat more radical idea is to slice up multidimensional arrays into parallel single one-dimension arrays: * An array of ints is a much better than an array of Integers, but this also generalizes to the fact that two parallel arrays of ints are also a lot more efficient than an array of (int,int) objects. The same goes for any combination of primitive types. * If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[] and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects. (The exception to this, of course, is when you're designing an API for other code to access; in those cases, it's usually better to trade correct API design for a small hit in speed. But in your own internal code, you should try and be as efficient as possible.) Generally speaking, avoid creating short-term temporary objects if you can. Fewer objects created mean less-frequent garbage collection, which has a direct impact on user experience.
__________________ cheers Aman |
| |||
| Use Native Methods When processing strings, don't hesitate to use specialty methods like String.indexOf(), String.lastIndexOf(), and their cousins. These are typically implemented in C/C++ code that easily runs 10-100x faster than doing the same thing in a Java loop. The flip side of that advice is that punching through to a native method is more expensive than calling an interpreted method. Don't use native methods for trivial computation, if you can avoid it.
__________________ cheers Aman |
| |||
| Prefer Virtual Over Interface Suppose you have a HashMap object. You can declare it as a HashMap or as a generic Map: Code: Map myMap1 = new HashMap(); HashMap myMap2 = new HashMap(); Conventional wisdom says that you should prefer Map, because it allows you to change the underlying implementation to anything that implements the Map interface. Conventional wisdom is correct for conventional programming, but isn't so great for embedded systems. Calling through an interface reference can take 2x longer than a virtual method call through a concrete reference. If you have chosen a HashMap because it fits what you're doing, there is little value in calling it a Map. Given the availability of IDEs that refactor your code for you, there's not much value in calling it a Map even if you're not sure where the code is headed. (Again, though, public APIs are an exception: a good API usually trumps small performance concerns.)
__________________ cheers Aman |
| |||
| Prefer Static Over Virtual If you don't need to access an object's fields, make your method static. It can be called faster, because it doesn't require a virtual method table indirection. It's also good practice, because you can tell from the method signature that calling the method can't alter the object's state.
__________________ cheers Aman |
| |||
| Avoid Internal Getters/Setters In native languages like C++ it's common practice to use getters (e.g. i = getCount()) instead of accessing the field directly (i = mCount). This is an excellent habit for C++, because the compiler can usually inline the access, and if you need to restrict or debug field access you can add the code at any time. On Android, this is a bad idea. Virtual method calls are expensive, much more so than instance field lookups. It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.
__________________ cheers Aman |
| |||
| Declare Constants Final Consider the following declaration at the top of a class: Code: static int intVal = 42; static String strVal = "Hello, world!"; The compiler generates a class initializer method, called <clinit>, that is executed when the class is first used. The method stores the value 42 into intVal, and extracts a reference from the classfile string constant table for strVal. When these values are referenced later on, they are accessed with field lookups. We can improve matters with the "final" keyword: Code: static final int intVal = 42; static final String strVal = "Hello, world!"; The class no longer requires a <clinit> method, because the constants go into classfile static field initializers, which are handled directly by the VM. Code accessing intVal will use the integer value 42 directly, and accesses to strVal will use a relatively inexpensive "string constant" instruction instead of a field lookup. Declaring a method or class "final" does not confer any immediate performance benefits, but it does allow certain optimizations. For example, if the compiler knows that a "getter" method can't be overridden by a sub-class, it can inline the method call. You can also declare local variables final. However, this has no definitive performance benefits. For local variables, only use "final" if it makes the code clearer (or you have to, e.g. for use in an anonymous inner class).
__________________ cheers Aman |
![]() |
| Thread Tools | |
| Display Modes | |
| |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| SAP Tips & Tricks | leoraja8 | Operating Systems | 0 | 03-29-2008 12:11 AM |
| C# .Net Tips & Tricks | oxygen | C# Programming | 82 | 03-13-2008 08:19 AM |
| PHP Tips and Tricks | Sabari | PHP Programming | 20 | 12-18-2007 05:26 AM |
| .NET tricks & Tips | Karpagarajan | VB.NET Programming | 1 | 04-23-2007 08:17 AM |
| SEO Tips & Tricks | spid4r | Search Engine Optimization | 0 | 03-08-2007 11:03 PM |