Android之序列化

来源:互联网 发布:2017淘宝双11红包 编辑:程序博客网 时间:2024/05/22 15:40

Android的两种序列化


序列化的目的?

用于在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

<span style="font-size:18px;">// access modifiers, accessors and constructors omitted for brevitypublic class Student implements Serializable    String name;    int age;}Student student = new Student("king","20");//Passing MyObjects instance via intentIntent mIntent = new Intent(FromActivity.this, ToActivity.class);mIntent.putExtra("UniqueKey", student);//Getting MyObjects instanceIntent mIntent = getIntent();Student received_student = (Student) mIntent.getSerializableExtra("UniqueKey");</span>

首先它写代码非常简洁,但是由于它使用了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 intentIntent mIntent = new Intent(FromActivity.this, ToActivity.class);mIntent.putExtra("UniqueKey", student);//Getting MyObjects instanceIntent 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的接口
1 0
原创粉丝点击