I have been working to find an efficient way to serialize a specific class to pass between my server and client and have been using ByteOutputArrayStream to pass around a byte array. However, this article makes me wonder if I should be using ByteOutputArrayStream at all. Here is the codec I use to serialize and deserialize a class called 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();
}
The class PackagedData looks like:
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;
}
}
My two questions are: Should I use a ByteArrayOutputStream? If so, what should I set the buffer size to in the parameter? I understand ByteArrayOutputStream increases buffer size as needed but I figure that will just take more resources and time than initializing it at a proper buffer size in the first place.
Thank you in advance.
ByteArrayOutputStreamis fine, and is almost certainly not the bottleneck in this code – though, sure, you could eliminate it here. What really sucks is the native Java serialization, and should be avoided, both in terms of speed and output size. github.com/eishay/jvm-serializers/wikiByteArrayOutputStreamwhen I first initialize it? Or would the default 32 buffer size be alright? There is no limitation on the size of the key/value that will be stored in thePackaged Dataand the class types of key/value may even change later as the code evolves.ByteArrayOutputStreamis the bottleneck in your code. As with any performance concern: you must measure.ByteArrayOutputStreamis redundant. It adds latency. It is literally a waste of time space.