I found two ways how to read and write using Kryo generically and I am thinking if one of them is better or worse or if they are just the same.
Option 1 - using kryo function writeClassAndObject (readClassAndObject)
public <T> void writeK(T obj, String fileName) {
checkDir(path);
Kryo kryo = new Kryo();
Output output = null;
try {
output = new Output(new FileOutputStream(homePath + path + "/" + "kryo_" + fileName + ".bin"));
kryo.writeClassAndObject(output, obj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
output.close();
}
}
Option 2 - using writeObject (readObject) and Class information
public <T> void writeKryo(Class<T> cl, T obj, String fileName) {
checkDir(path);
Kryo kryo = new Kryo();
kryo.register(cl);
Output output = null;
try {
output = new Output(new FileOutputStream(homePath + path + "/" + "kryo_" + fileName + ".bin"));
kryo.writeObject(output, obj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
output.close();
}
}
It would seem that second option is better because when calling the function I specify what class is that so Java doesn't need to figure out itself. But not sure if that's true or not. According to the speed they seem comparable. Thanks
This depends on whether you can know from the context what instance of a class the serialized data represents at the time you deserialize your data. When using writeClassAndObject
, you do not need to specify the class when you are reading the object. You can deserialize the data and then call getClass
on this instance.
In contrast, when using writeObject
, you do need to know the class of the stored object when reading it. Otherwise, you cannot deserialize the data as the information is not stored in the serialization data.
When (de-)serializing one object, it does not really matter which approach you choose, given that you can choose both. However, imagine a scenario where you serialize instances of the same class again and again. The serialization data can be reduced in size significantly when not storing the class with every instance. Instead, you could for example serialize the class name at the beginning of the file or even simply hard-code it into you deserializer.