android Serializable 和 Parcelable 區別

來源:互聯網
上載者:User

標籤:android   des   style   blog   color   使用   

 

android 中自訂的對象序列化的問題有兩個選擇一個是Parcelable,另外一個是Serializable。

一 序列化原因:

1.永久性儲存對象,儲存對象的位元組序列到本地檔案中;
2.通過序列化對象在網路中傳遞對象;
3.通過序列化在進程間傳遞對象。 

二 至於選取哪種可參考下面的原則:

1.在使用記憶體的時候,Parcelable 類比Serializable效能高,所以推薦使用Parcelable類。
2.Serializable在序列化的時候會產生大量的臨時變數,從而引起頻繁的GC。
3.Parcelable不能使用在要將資料存放區在磁碟上的情況,因為Parcelable不能很好的保證資料的持久性在外界有變化的情況下。儘管Serializable效率低點, 也不提倡用,但在這種情況下,還是建議你用Serializable 。


實現:
1 Serializable 的實現,只需要繼承  implements Serializable 即可。這隻是給對象打了一個標記,系統會自動將其序列化。

2 Parcelabel 的實現,需要在類中添加一個靜態成員變數 CREATOR,這個變數需要繼承 Parcelable.Creator 介面。

public class MyParcelable implements Parcelable {     private int mData;     public int describeContents() {         return 0;     }     public void writeToParcel(Parcel out, int flags) {         out.writeInt(mData);     }     public static final Parcelable.Creator<MyParcelable> CREATOR             = new Parcelable.Creator<MyParcelable>() {         public MyParcelable createFromParcel(Parcel in) {             return new MyParcelable(in);         }         public MyParcelable[] newArray(int size) {             return new MyParcelable[size];         }     };          private MyParcelable(Parcel in) {         mData = in.readInt();     } }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.