Android App Performance

Preview:

Citation preview

Android App PerformanceAltaf ur Rehman

Avoid Creating Unnecessary objects

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

Avoid Internal Getter/Setter

• Android uses Indexing mechanism for methods. • Direct field access is about 7x faster than invoking a getter • Moral of story don’t create unnecessary methods.

Prefer Static Over Virtual• If you don't need to access an object's fields,

make your method static. Invocations will be about 15%-20% faster. It's also good practice, because you can tell from the method signature that calling the method can't alter the object's state.

Use Static Final For Constants• Consider the following declaration. • static int intVal = 42; • static String strVal = "Hello, world!”; • We can improve matters with the "final" keyword • static final int intVal = 42; • static final String strVal = "Hello, world!";

Use Enhanced For Loop Syntax

• Use enhanced for loop(sometimes called for-each) • 3x times faster than Iterable interface.

Recycle Complex Java objects

• We have a GC, but usually better to just create

less garbage that it has to clean up. • BitmapFactory.recyle() • Matcher.reset(newString) • StringBuilder.setLength(0)

Avoid Using Floating-Point

• As a rule of thumb, floating-point is about 2x slower than integer on Android-powered devices.

• In speed terms, there's no difference between float and double on the more modern hardware. Space-wise, double is 2x larger. As with desktop machines, assuming space isn't an issue, you should prefer double to float.

Know and Use the Libraries

• Don’t re-invent the wheel. • System.arrayCopy() is 9x faster then hand-coded

looped copy. • It is not applied to third party libraries • Moral of the story “Know your resources”

Myths• On devices without a JIT, it is true that invoking methods

via a variable with an exact type rather than an interface is slightly more efficient. (So, for example, it was cheaper to invoke methods on a HashMap map than a Map map, even though in both cases the map was a HashMap.) It was not the case that this was 2x slower; the actual difference was more like 6% slower. Furthermore, the JIT makes the two effectively indistinguishable.

Use ViewHolder Pattern

Use Native Methods Carefully

• Developing your app with native code using the Android NDK isn't necessarily more efficient than programming with the Java language.

• Native code is primarily useful when you have an existing native codebase that you want to port to Android, not for "speeding up" parts of your Android app written with the Java language.

Background continuous processing

• Threads

• Handler.

• BroadcastReceiver

• User AlarmManager for continuous running task.

Re-using Layout

• Use <include> Tag • Use <merge> Tag

Recommended