출처: http://www.developerphil.com/parcelable-vs-serializable/
http://aroundck.tistory.com/2477
When starting on Android, we all learn that we cannot just pass object references to activities and fragments
, we have to put those in an Intent / Bundle.
Looking at the api, we realize that we have two options, we can either make our objects Parcelable orSerializable.
As Java developers, we already know of the Serializable mechanism, so why bother with Parcelable?
To answer this, lets take a look at both approaches.
Serializable, the Master of Simplicity
| // access modifiers, accessors and constructors omitted for brevity
public class SerializableDeveloper implements Serializable
String name;
int yearsOfExperience;
List<Skill> skillSet;
float favoriteFloat;
static class Skill implements Serializable {
String name;
boolean programmingRelated;
}
}
|
The beauty of serializable is that you only need to implement the Serializable interface on a class and its children.
It is a marker interface, meaning that there is no method to implement, Java will simply do its best effort to serialize it efficiently.
The problem with this approach is that reflection is used and it is a slow process.
This mechanism also tends to create a lot of temporary objects and cause quite a bit of garbage collection.
Parcelable, the Speed King
| // access modifiers, accessors and regular constructors ommited for brevity
class ParcelableDeveloper implements Parcelable {
String name;
int yearsOfExperience;
List<Skill> skillSet;
float favoriteFloat;
ParcelableDeveloper(Parcel in) {
this.name = in.readString();
this.yearsOfExperience = in.readInt();
this.skillSet = new ArrayList<Skill>();
in.readTypedList(skillSet, Skill.CREATOR);
this.favoriteFloat = in.readFloat();
}
void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(yearsOfExperience);
dest.writeTypedList(skillSet);
dest.writeFloat(favoriteFloat);
}
int describeContents() {
return 0;
}
static final Parcelable.Creator<ParcelableDeveloper> CREATOR
= new Parcelable.Creator<ParcelableDeveloper>() {
ParcelableDeveloper createFromParcel(Parcel in) {
return new ParcelableDeveloper(in);
}
ParcelableDeveloper[] newArray(int size) {
return new ParcelableDeveloper[size];
}
};
static class Skill implements Parcelable {
String name;
boolean programmingRelated;
Skill(Parcel in) {
this.name = in.readString();
this.programmingRelated = (in.readInt() == 1);
}
@Override
void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(programmingRelated ? 1 : 0);
}
static final Parcelable.Creator<Skill> CREATOR
= new Parcelable.Creator<Skill>() {
Skill createFromParcel(Parcel in) {
return new Skill(in);
}
Skill[] newArray(int size) {
return new Skill[size];
}
};
@Override
int describeContents() {
return 0;
}
}
}
|
According to google engineers, this code will run significantly faster.
One of the reasons for this is that we are being explicit about the serialization process instead of using reflection to infer it.
It also stands to reason that the code has been heavily optimized for this purpose.
However, it is obvious here that implementing Parcelable is not free.
There is a significant amount of boilerplate code and it makes the classes harder to read and maintain.
Speed Tests
Of course, we want to know how much faster Parcelable is.
The methodology
- Mimic the process of passing object to an activity by putting an object in a bundle and calling Bundle#writeToParcel(Parcel, int)
and then fetching it back - Run this in a loop 1000 times
- Do an average on 10 separate runs to account for memory allocation, other apps using the cpu, etc
- The object under test are the SerializableDeveloper and the ParcelableDeveloper shown above
- Test on multiple devices - android versions
- LG Nexus 4 - Android 4.2.2
- Samsung Nexus 10 - Android 4.2.2
- HTC Desire Z - Android 2.3.3
The results
Nexus 10
Serializable: 1.0004ms, Parcelable: 0.0850ms - 10.16x improvement.
Nexus 4
Serializable: 1.8539ms - Parcelable: 0.1824ms - 11.80x improvement.
Desire Z
Serializable: 5.1224ms - Parcelable: 0.2938ms - 17.36x improvement.
There you have it: Parcelable is more than 10x faster than Serializable!
It is also interesting to note that even on a Nexus 10, a pretty simple object can take about
1 millisecond to go through a full serialize/deserialize cycle.
The Bottom Line
If you want to be a good citizen, take the extra time to implement Parcelable since it will perform 10 times faster and use less resources.
However, in most cases, the slowness of Serializable won’t be noticeable.
Feel free to use it but remember that serialization is an expensive operation so keep it to a minimum.
If you are trying to pass a list with thousands of serialized objects, it is possible that the whole process will take more than a second.
It can make transitions or rotation from portrait to landscape feel very sluggish.
Serializable 은 Java 만 아는 사람이라면 쉽게 알 수 있는 serialization 방법.
그냥 Serializable 을 implementation 만 해주면, serialize 가 필요한 순간에 알아서 serialze 해주는 편리한 marker interface.
그러나, mobile 시대가 강림하면서 등장한 유망한 어린이(?) 가 있으니 그는 바로 Parcelable.
이 녀석은 IPC ( Inter Process Communication ) 에 최적화된 녀석으로. Serialize 보다 속도가 빠르다.
물론, 해야 하는 일은 Serialize 보다 훨씬 많다.
직접 serialize 되어야 할 녀석들을 선별해서 그것을 쓰고 읽는 작업을 해주어야 한다.
그럼 왜 serialization 이 parcelable 보다 속도가 느릴까?
그 이유는, serialization 은 reflection 방법을 사용하여 serialization 을 하는데, parcelable 은 프로그래머가 직접 바로 setting 을 해주기 때문에
빠른 것이다. ( reflection 이 성능이슈를 야기할 수 있다는 것은 이미 알고 있을꺼라 생각한다.. )
다행스럽게도 둘의 성능차이가 얼마나 날까 테스트 결과를 찾아봤는데 이런 결과를 볼 수 있었다.
결론적으로 보면, Serialization 도 그렇게 느리지는 않지만, Parcelable 이 훨씬 빠르다.
정말 많은 뭉태기의 property 들이 한 클래스에 있는 경우는 드물겠지만, 그런 경우라면 Parcelable 의 성능이 훨씬 빠르겠고..
IPC 가 많이 발생하는 경우라면, 가랑비에 옷 젖는 줄 모른다고, 작은 성능 차이가 결국 최적화에 엄청난 영향을 미칠 수 있다.
결국 정말 특별한 이유가 없다면, 사실 귀찮더라도 Serializable 보다는 Parcelable 을 사용하는 것이 추천된다.
'IT_Programming > Android_Java' 카테고리의 다른 글
[펌] 안드로이드 Custom Component 만들기 (0) | 2015.07.15 |
---|---|
[android] get sender number in SMS, MMS broadcast receiver (0) | 2015.07.08 |
[펌] Beacon(Bluetooth 4.0 Based) 프로토타이핑 - 비콘 클라이언트 아키텍처 (0) | 2015.07.07 |
[안드로이드 UI최적화] 나인패치의 모든것 / DPI, DIP(DP) 개념 (0) | 2015.07.01 |
Android Support Library (0) | 2015.07.01 |