本文主要介绍了两种序列化实现与它们的性能对比,还有序列化开源库的介绍。
序列化的目的?
用于在activities之间传递Intent参数时,如果需要传递的的是对象(pass objects to activities),使用序列化就可以方便的传递。
序列化使用方法
只有两个序列化,一个是Serializable [siəriəlaɪ'zəbl],一个是Parcelable,他们都有各自的特点.
Serializable
WIKI
http://developer.android.com/reference/java/io/Serializable.html
Usage
// access modifiers, accessors and constructors omitted for brevity
public class Student implements Serializable
String name;
int age;
}
Student student = new Student("king","20");
//Passing MyObjects instance via intent
Intent mIntent = new Intent(FromActivity.this, ToActivity.class);
mIntent.putExtra("UniqueKey", student);
//Getting MyObjects instance
Intent mIntent = getIntent();
Student received_student = (Student) mIntent.getSerializableExtra("UniqueKey");
Features:
首先它写代码非常简洁,但是由于它使用了Java的反射机制,所以它会比较慢,同时反射机制也会产生许多临时对象,占用了GC(Gargage Collection)活动,目前来说,反射对jvm的运算压力不是很大,主要是内存压力比较大。
Parcelable
WIKI
http://developer.android.com/reference/android/os/Parcelable.html
Usage
public class Student implements Parcelable {
String name;
int age;
@Override public int describeContents() {
return 0;
}
@Override public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
dest.writeInt(this.age);
}
public Student() {
}
private Student(Parcel in) {
this.name = in.readString();
this.age = in.readInt();
}
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
public Student createFromParcel(Parcel source) {
return new Student(source);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
}
Student student = new Student("king","20");
//Passing MyObjects instance via intent
Intent mIntent = new Intent(FromActivity.this, ToActivity.class);
mIntent.putExtra("UniqueKey", student);
//Getting MyObjects instance
Intent mIntent = getIntent();
Student received_student = (Student) mIntent.getParcelable("UniqueKey");
Features
由于在一个代码中加入了很多Parcelable的代码,导致产生许多样板代码(a significant amount of boilerplate code),冗长难看;与此同时,由于我们明确的指出了序列化的过程,所以它没有反射,相比Serializable性能更好;
Parcelable VS Serializable
- 如果只是偶尔使用的话,使用Serializable即可,忘掉它的性能影响吧
- 判断一个函数的性能,运行上千上万遍才能看出来
- Parcelable有着至少10X的性能。
- 当然在你传递上千个对象的时候,必须要使用Parcelable。
- 当你要使用反射时,你完全可以用别外一种更好的方式的实现,如代码生成器,动态语言,下面有开源库介绍。
- 当你的程序运行缓慢的话,永远不要怪反射或者Java虚拟机,Talk is cheap,show me the code.
- Map里实现了Serializable接口,而在Bundle实现了Parcelable的接口
有什么好的序列化开源库?
-
注解工具,性能可以去看performance-test.
-
注解工具,同上.
-
android-parcelable-intellij-plugin
intellij插件,自动生成Parceler样板代码(bolilerplate code),不影响性能,我喜欢用这个,
CMD
+N
即可自动生成