我一直在努力寻找一种有效的方法来序列化一个特定的类,以便在我的服务器和客户端之间传递,并且一直使用ByteOutputArrayStream传递一个字节数组。但是,this article让我想知道我是否应该使用ByteOutputArrayStream。这是我用来序列化和反序列化名为PackagedData
的类的编解码器:
public final PackagedData decode(final byte[] data) {
final ByteArrayInputStream bstream = new ByteArrayInputStream(data);
final PackagedData result;
try (final ObjectInputStream ois = new ObjectInputStream(bstream)) {
result = (PackagedData)ois.readObject();
}catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e.getCause());
}
return result;
}
public final byte[] encode(final PackagedData packagedData) {
final ByteArrayOutputStream bstream = new ByteArrayOutputStream();
try (final ObjectOutputStream oos = new ObjectOutputStream(bstream)) {
oos.writeObject(packagedData);
}
catch (IOException e) {
throw new RuntimeException(e.getCause());
}
return bstream.toByteArray();
}
班级PackagedData
如下:
public final class PackagedData implements Serializable {
private final String dataType;
private final String key;
private final Integer value;
public PackagedData(final String dataType, final String key, final Integer value) {
this.dataType = dataType;
this.key = key;
this.value = value;
}
public final String getType(){
return dataType;
}
public final String getKey() {
return key;
}
public final Integer getValue() {
return value;
}
}
我的两个问题是:我应该使用ByteArrayOutputStream吗?如果是这样,我应该在参数中设置缓冲区大小?我理解ByteArrayOutputStream会根据需要增加缓冲区大小,但我认为这比仅在适当的缓冲区大小初始化它只需要更多的资源和时间。
提前谢谢。
答案 0 :(得分:1)
如果您想提高对象Serialization
的效率,我强烈建议您使用类似
Externalizable
public final class PackagedData implements Externalizable {
private String dataType;
private String key;
private Integer value;
public PackagedData(final String dataType, final String key,
final Integer value) {
this.dataType = dataType;
this.key = key;
this.value = value;
}
public String getType() {
return dataType;
}
public String getKey() {
return key;
}
public Integer getValue() {
return value;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(this.dataType);
out.writeUTF(this.key);
out.writeInt(this.value);
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
this.dataType = in.readUTF();
this.key = in.readUTF();
this.value = in.readInt();
}
}
如果序列化PackageData
是真正关键的代码,您应该会看到显着的性能改进。