Android之序列化

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 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");</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 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的接口
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值