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
如果有些field不會變,加上Final增加存取的速度!
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。
No comments:
Post a Comment