本人從事java服務器端開發已經有6,7年了,最近這一年多轉去作Android開發。到今天以爲應該把本身的一些感覺寫下來,供之後參考。 java
1. Java bean的定義 數組
咱們通常定義一個java bean,都是用以下的代碼: 服務器
public class User { private String name; public void setName(String name) { this.name = name; } public String getName() { return this.name; } }
在Android開發中,咱們通常這樣定義一個java bean: ide
public class User { public String name; }
在Android的官方開發文檔中這樣說到: 性能
In native languages like C++ it's common practice to use getters (i = getCount()) instead of accessing the field directly (i = mCount). This is an excellent habit for C++ and is often practiced in other object oriented languages like C# and Java, 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.而對Android開發來講:
However, this is a bad idea on Android. 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.
沒有JIT的話,直接訪問成員的速度是經過getter/setter訪問速度是3倍。有JIT的話,這個數字是7倍。 學習
2. 儘可能少的建立臨時對象,儘可能使用基本類型 this
在服務器端開發的時候,咱們不多會注意這個問題。可是在Android開發中,這些就是咱們必需要留意。我我的認爲咱們在服務器端開發的時候,也能夠應用這個原則。 idea
由於Android內存受限,減小內存分配,就意味着減小沒必要要的垃圾回收,進而能夠避免App在使用中出現停頓等現象。 debug
好比說方法的返回值能用基本類型的表示的,就不要用一個java bean來表示;能用一個基本類型的數組表示的,就不要用一個java bean數組來表示。 rest
3. 不要用反射,除非無路可走。
這個對App的性能是一個很是大的損耗。除非是爲了App開發中爲了OS不用版本的兼容性而使用反射。
4. 使用最小的空間來存儲更多的數據
經過學習和使用,Android裏面有一種很是高效的數據存儲方式:
public void writeToParcel(Parcel dest, int flags) { dest.writeLong(time); int bat = (((int)cmd)&0xff) | ((((int)batteryLevel)<<8)&0xff00) | ((((int)batteryStatus)<<16)&0xf0000) | ((((int)batteryHealth)<<20)&0xf00000) | ((((int)batteryPlugType)<<24)&0xf000000); dest.writeInt(bat); }
Android用一個int存儲了5個數據項。這段代碼來自於Android 存儲電池歷史文件源代碼。這段代碼給我了不少的啓示。當咱們想把一些數據存儲在文件中,就能夠用這種方式:緊湊,快速。
最後一個是選擇了一個新的IDE: Android Studio和Intellij Idea。用了新的IDE以後,開發效率確實提升了不很多,並且心情也愉悅了不少。