Sunday, January 23, 2011

Android 電量控管和效能之路

在android SDK的Dev guide裡︰

Designing for Performance單元


1.Avoid Creating Objects

  • 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. 叫我們少用New String而用StringBuilder
  • 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.  最好避免二維陣列的使用,而使用多個一維陣列

2.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. 盡量使用Static method

3.Avoid Internal Getters/Setters

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.  有時候我們做Getter/Setter是為了OO,但是若在程式內部,就免了吧!

4.Use Static Final For Constants


5.Use Enhanced For Loop Syntax

  public void two() {
        int sum = 0;
        for (Foo a : mArray) {
            sum += a.mSplat;

6.Avoid Enums Where You Only Need Ints

you should consider static final int constants instead.   避免使用Enum。

7.Use Floating-Point Judiciously

As a rule of thumb, floating-point is about 2x slower than integer on Android devices. This is true on a FPU-less, JIT-less G1 and a Nexus One with an FPU and the JIT. (Of course, absolute speed difference between those two devices is about 10x for arithmetic operations.)  避免使用Float。

8.Know And Use The Libraries

9.Use Native Methods Judiciously

No comments: