提問:
什么是序列化?
為什么要序列化?
為什么要使用Parcelable?
Parcelable與Serializable的區(qū)別?
1. 序列化 :
序列化是一個(gè)過程,是將對象狀態(tài)轉(zhuǎn)成可以存儲或者傳輸?shù)倪^程。
2. Android中對象序列化的目的:
- 用于進(jìn)程之間的對象傳遞;
- 用于網(wǎng)絡(luò)之間的對象傳遞;
- 用于存儲,實(shí)現(xiàn)數(shù)據(jù)的持久化
3. 關(guān)于Parcelable
Parcelable:
Interface for classes whose instances can be written to and restored from a Parcel.
可以在Parcel中寫入實(shí)例并從其中恢復(fù)的類的接口。
image.png
根據(jù)官方文檔的說明,我們可以知道
- IBinder是傳輸?shù)妮d體;
- google將其設(shè)計(jì)為高性能的IPC傳輸
- 不適合將任何Parcel數(shù)據(jù)放入持久存儲中
4. Parcelable與Serializable
- Android中推薦使用Parcelable,在內(nèi)存占用(Parcelable開銷小)以及性能方面優(yōu)于 Serializable;Parcelable在內(nèi)存中直接進(jìn)行讀寫,而Serializable是通過IO流的形式將數(shù)據(jù)讀寫入在硬盤上,內(nèi)存讀寫速度>硬盤讀寫速度,因此更適用于Android中Activity傳輸數(shù)據(jù);
- Serializable序列化時(shí)會產(chǎn)生大量的臨時(shí)變量,引起頻繁的GC;
- 上面已經(jīng)提到,Parcelable不適合保證數(shù)據(jù)的持續(xù)性,因此當(dāng)要存儲時(shí)還是選擇Serializable。
參考:https://developer.android.com/reference/android/os/Parcel.html
