在程式設計開發中,記憶體的占用是我們經常要面對的現實,通常的記憶體調優的方向就是盡量減少記憶體的占用。這其中避免建立不必要的對象是一項重要的方面。
android裝置不像pc那樣有着足夠大的記憶體,而且單個app占用的記憶體實際上是比較小的。是以避免建立不必要的對象對于android開發尤為重要。
本文會介紹一些常見的避免建立對象的場景和方法,其中有些屬于微優化,有的屬于編碼技巧,當然也有确實能夠起到顯著效果的方法。
使用單例
單例是我們常用的設計模式,使用這種模式,我們可以隻提供一個對象供全局調用。是以單例是避免建立不必要的對象的一種方式。
單例模式上手容易,但是需要注意很多問題,最重要的就是多線程并發的情況下保證單例的唯一性。當然方式很多,比如餓漢式,懶漢式double-check等。這裡介紹一個很極客的書寫單例的方式。
public static class singleinstance {
private singleinstance() {
}
public static singleinstance getinstance() {
return singleinstanceholder.sinstance;
}
private static class singleinstanceholder {
private static singleinstance sinstance = new singleinstance();
}
}
在java中,類的靜态初始化會在類被加載時觸發,我們利用這個原理,可以實作利用這一特性,結合内部類,可以實作上面的代碼,進行懶漢式建立執行個體。
避免進行隐式裝箱
自動裝箱是java 5 引入的一個特性,即自動将原始類型的資料轉換成對應的引用類型,比如将int轉為integer等。
這種特性,極大的減少了編碼時的瑣碎工作,但是稍有不注意就可能建立了不必要的對象了。比如下面的代碼
integer sum = 0;
for (int i = 1000; i < 5000; i++) {
sum += i;
上面的代碼sum+=i可以看成sum = sum + i,但是+這個操作符不适用于integer對象,首先sum進行自動拆箱操作,進行數值相加操作,最後發生自動裝箱操作轉換成integer對象。其内部變化如下
int result = sum.intvalue() + i;
integer sum = new integer(result);
由于我們這裡聲明的sum為integer類型,在上面的循環中會建立将近4000個無用的integer對象,在這樣龐大的循環中,會降低程式的性能并且加重了垃圾回收的工作量。是以在我們程式設計時,需要注意到這一點,正确地聲明變量類型,避免因為自動裝箱引起的性能問題。
另外,當将原始資料類型的值加入集合中時,也會發生自動裝箱,是以這個過程中也是有對象建立的。如有需要避免這種情況,可以選擇sparsearray,sparsebooleanarray,sparselongarray等容器。
謹慎選用容器
java和android提供了很多編輯的容器集合來組織對象。比如arraylist,contentvalues,hashmap等。
然而,這樣容器雖然使用起來友善,但也存在一些問題,就是他們會自動擴容,這其中不是建立新的對象,而是建立一個更大的容器對象。這就意味這将占用更大的記憶體空間。
以hashmap為例,當我們put key和value時,會檢測是否需要擴容,如需要則雙倍擴容
@override
public v put(k key, v value) {
if (key == null) {
return putvaluefornullkey(value);
//some code here
// no entry for (non-null) key is present; create one
modcount++;
if (size++ > threshold) {
tab = doublecapacity();
index = hash & (tab.length - 1);
addnewentry(key, value, hash, index);
return null;
關于擴容的問題,通常有如下幾種方法
預估一個較大的容量值,避免多次擴容
尋找替代的資料結構,確定做到時間和空間的平衡
用好launchmode
提到launchmode必然和activity有關系。正常情況下我們在manifest中聲明activity,如果不設定launchmode就使用預設的standard模式。
一旦設定成standard,每當有一次intent請求,就會建立一個新的activity執行個體。舉個例子,如果有10個撰寫郵件的intent,那麼就會建立10個composemailactivity的執行個體來處理這些intent。結果很明顯,這種模式會建立某個activity的多個執行個體。
如果對于一個搜尋功能的activity,實際上保持一個activity示例就可以了,使用standard模式會造成activity執行個體的過多建立,因而不好。
確定符合常理的情況下,合理的使用launchmode,減少activity的建立。
activity處理onconfigurationchanged
這又是一個關于activity對象建立相關的,因為activity建立的成本相對其他對象要高很多。
預設情況下,當我們進行螢幕旋轉時,原activity會銷毀,一個新的activity被建立,之是以這樣做是為了處理布局适應。當然這是系統預設的做法,在我們開發可控的情況下,我們可以避免重新建立activity。
以螢幕切換為例,在activity聲明時,加上
<activity
android:name=".mainactivity"
android:configchanges="orientation"
android:label="@string/app_name"
android:theme="@style/apptheme.noactionbar"/>
然後重寫activity的onconfigurationchanged方法
public void onconfigurationchanged(configuration newconfig) {
super.onconfigurationchanged(newconfig);
if (newconfig.orientation == configuration.orientation_portrait) {
setcontentview(r.layout.portrait_layout);
} else if (newconfig.orientation == configuration.orientation_landscape) {
setcontentview(r.layout.landscape_layout);
注意字元串拼接
字元串這個或許是最不起眼的一項了。這裡主要講的是字元串的拼接
log.i(logtag, "oncreate bundle=" + savedinstancestate);
這應該是我們最常見的打log的方式了,然而字元串的拼接内部實際是生成stringbuilder對象,然後挨個進行append,直至最後調用tostring方法的過程。
下面是一段代碼循環的代碼,這明顯是很不好的,因為這其中建立了很多的stringbuilder對象。
public void implicitusestringbuilder(string[] values) {
string result = "";
for (int i = 0; i < values.length; i++) {
result += values[i];
}
system.out.println(result);
降低字元串拼接的方法有
使用string.format替換
如果是循環拼接,建議顯式在循環外部建立stringbuilder使用
減少布局層級
布局層級過多,不僅導緻inflate過程耗時,還多建立了多餘的輔助布局。是以減少輔助布局還是很有必要的。可以嘗試其他布局方式或者自定義視圖來解決這類的問題。
提前檢查,減少不必要的異常
異常對于程式來說,在平常不過了,然後其實異常的代碼很高的,因為它需要收集現場資料stacktrace。但是還是有一些避免異常抛出的措施的,那就是做一些提前檢查。
比如,我們想要列印一個檔案的每一行字元串,沒做檢查的代碼如下,是存在filenotfoundexception抛出可能的。
private void printfilebyline(string filepath) {
try {
fileinputstream inputstream = new fileinputstream("textfile.txt");
bufferedreader br = new bufferedreader(new inputstreamreader(inputstream));
string strline;
//read file line by line
while ((strline = br.readline()) != null) {
// print the content on the console
system.out.println(strline);
}
br.close();
} catch (filenotfoundexception e) {
e.printstacktrace();
} catch (ioexception e) {
e.printstacktrace();
如果我們進行檔案是否存在的檢查,抛出filenotfoundexception的機率會減少很多,
if (!new file(filepath).exists()) {
return;
try {
fileinputstream inputstream = new fileinputstream("anonymous.txt");
bufferedreader br = new bufferedreader(new inputstreamreader(inputstream));
string strline;
while ((strline = br.readline()) != null) {
// print the content on the console
system.out.println(strline);
}
br.close();
上述的檢查是一個不錯的編碼技巧,建議采納。
不要過多建立線程
在android中,我們應該盡量避免在主線程中執行耗時的操作,因而需要使用其他線程。
private void testthread() {
new thread() {
@override
public void run() {
super.run();
//do some io work
}.start();
雖然這些能工作,但是建立線程的代價遠比普通對象要高的多,建議使用handlerthread或者threadpool做替換。
使用注解替代枚舉
枚舉是我們經常使用的一種用作值限定的手段,使用枚舉比單純的常量約定要靠譜。然後枚舉的實質還是建立對象。好在android提供了相關的注解,使得值限定在編譯時進行,進而減少了運作時的壓力。相關的注解為intdef和stringdef。
如下以intdef為例,介紹如何使用
在一個檔案中如下聲明
public class appconstants {
public static final int state_open = 0;
public static final int state_close = 1;
public static final int state_broken = 2;
@intdef({state_open, state_close, state_broken})
public @interface doorstate {
然後設定書寫這樣的方法
private void setdoorstate(@appconstants.doorstate int state) {
//some code
當調用方法時隻能使用state_open,state_close和state_broken。使用其他值會導緻編譯提醒和警告。
選用對象池
在android中有很多池的概念,如線程池,連接配接池。包括我們很長用的handler.message就是使用了池的技術。
比如,我們想要使用handler發送消息,可以使用message msg = new message(),也可以使用message msg = handler.obtainmessage()。使用池并不會每一次都建立新的對象,而是優先從池中取對象。
使用對象池需要需要注意幾點
将對象放回池中,注意初始化對象的資料,防止存在髒資料
合理控制池的增長,避免過大,導緻很多對象處于閑置狀态
謹慎初始化application
android應用可以支援開啟多個程序。 通常的做法是這樣
<service
android:name=".networkservice"
android:process=":network"/>
通常我們在application的oncreate方法中會做很多初始化操作,但是每個程序啟動都需要執行到這個oncreate方法,為了避免不必要的初始化,建議按照程序(通過判斷目前程序名)對應初始化.
public class myapplication extends application {
private static final string logtag = "myapplication";
@override
public void oncreate() {
string currentprocessname = getcurrentprocessname();
log.i(logtag, "oncreate currentprocessname=" + currentprocessname);
super.oncreate();
if (getpackagename().equals(currentprocessname)) {
//init for default process
} else if (currentprocessname.endswith(":network")) {
//init for netowrk process
}
}
private string getcurrentprocessname() {
string currentprocessname = "";
int pid = android.os.process.mypid();
activitymanager manager = (activitymanager) this.getsystemservice(context.activity_service);
for (activitymanager.runningappprocessinfo processinfo : manager.getrunningappprocesses()) {
if (processinfo.pid == pid) {
currentprocessname = processinfo.processname;
break;
}
return currentprocessname;
上面的一些知識就是關于android中如何避免建立多餘對象的總結.歡迎提出意見和觀點,共同進步.
作者:anonymoussf
來源:51cto