So sánh Parcelable vs Serializable
Cả hai đều dùng để chuyển đổi object thành byte stream để truyền dữ liệu giữa các component (Activity, Fragment, Service...), nhưng có sự khác biệt quan trọng về hiệu năng và cách triển khai.
Serializable
Serializable là một marker interface (interface rỗng, không có phương thức nào). Nó chuyển đổi object thành byte stream để truyền dữ liệu giữa các activity.
Ưu điểm: Triển khai rất đơn giản - chỉ cần implements Serializable.
Nhược điểm: Chậm hơn Parcelable do sử dụng reflection (phản xạ) và tạo nhiều object tạm thời trong quá trình serialize/deserialize.
Ví dụ Serializable
import java.io.Serializable;
class SerializableObject implements Serializable {
String name;
public SerializableObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Parcelable
Parcelable là interface riêng của Android, nhanh hơn Serializable đáng kể. Nó cũng chuyển object thành byte stream nhưng không dùng reflection, thay vào đó yêu cầu developer tự viết code đọc/ghi dữ liệu.
Ưu điểm: Hiệu năng cao, không tạo nhiều object tạm, được tối ưu cho Android IPC (Inter-Process Communication).
Nhược điểm: Code triển khai phức tạp hơn, phải viết thủ công các phương thức read/write.
Ví dụ Parcelable
import android.os.Parcel;
import android.os.Parcelable;
class ParcelableObject implements Parcelable {
private String name;
// Constructor đọc từ Parcel
protected ParcelableObject(Parcel in) {
this.name = in.readString();
}
// Constructor thông thường
public ParcelableObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// CREATOR bắt buộc - dùng để tạo object từ Parcel
public static final Creator<ParcelableObject> CREATOR = new Creator<ParcelableObject>() {
@Override
public ParcelableObject createFromParcel(Parcel in) {
return new ParcelableObject(in);
}
@Override
public ParcelableObject[] newArray(int size) {
return new ParcelableObject[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.name);
}
}
Bảng so sánh tóm tắt
| Tiêu chí | Serializable | Parcelable |
|---|---|---|
| Tốc độ | Chậm (dùng reflection) | Nhanh (tối ưu cho Android) |
| Độ phức tạp code | Rất đơn giản | Phức tạp hơn |
| Object tạm tạo ra | Nhiều | Ít |
| Khuyến nghị | Dữ liệu đơn giản, ít dùng | Dữ liệu phức tạp, truyền nhiều lần |
Khi nào dùng cái nào?
- Serializable: Dữ liệu nhỏ, ít lần truyền, ưu tiên tốc độ phát triển
- Parcelable: Dữ liệu lớn, truyền nhiều lần (Intent, Bundle), cần hiệu năng cao
- Mẹo: Android Studio có thể tự động generate code Parcelable (Alt+Insert → Parcelable)