I thought the performance of Java built-in serialization should be good. Compare to Gson, it doesn't need to do the lexical analysis, it should be faster than Gson.
But in my test, the result is just the opposite. See my code:
package cleancode;
import com.google.gson.Gson;
import java.io.*;
public class SerializationPerformanceTest {
public static final int MAX_LOOP = 1000000;
public static void main(String[] args) throws Exception {
trySerialization();
tryGson();
}
private static void tryGson() {
long start = System.currentTimeMillis();
Gson gson = new Gson();
for (int i = 0; i < MAX_LOOP; i++) {
String json = gson.toJson(createUser());
gson.fromJson(json, User.class);
}
long end = System.currentTimeMillis();
System.out.println("Gson cost: " + (end - start) + "ms");
}
private static void trySerialization() throws IOException, ClassNotFoundException {
long start = System.currentTimeMillis();
for (int i = 0; i < MAX_LOOP; i++) {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(byteStream);
stream.writeObject(createUser());
byte[] binary = byteStream.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(binary);
ObjectInputStream input = new ObjectInputStream(byteArrayInputStream);
input.readObject();
}
long end = System.currentTimeMillis();
System.out.println("Serialization cost: " + (end - start) + "ms");
}
private static User createUser() {
User user = new User();
user.setAaa(newValue());
user.setBbb(newValue());
user.setCcc(newValue());
user.setDdd(newValue());
user.setEee(newValue());
user.setFff(newValue());
user.setGgg(newValue());
return user;
}
private static String newValue() {
return "" + System.currentTimeMillis();
}
}
The class User
which is a java bean:
class User implements Serializable {
private String aaa;
private String bbb;
private String ccc;
private String ddd;
private String eee;
private String fff;
private String ggg;
String getAaa() {
return aaa;
}
void setAaa(String aaa) {
this.aaa = aaa;
}
String getBbb() {
return bbb;
}
void setBbb(String bbb) {
this.bbb = bbb;
}
String getCcc() {
return ccc;
}
void setCcc(String ccc) {
this.ccc = ccc;
}
String getDdd() {
return ddd;
}
void setDdd(String ddd) {
this.ddd = ddd;
}
String getEee() {
return eee;
}
void setEee(String eee) {
this.eee = eee;
}
String getFff() {
return fff;
}
void setFff(String fff) {
this.fff = fff;
}
String getGgg() {
return ggg;
}
void setGgg(String ggg) {
this.ggg = ggg;
}
}
The result in my computer:
Serialization cost: 12339ms
Gson cost: 3971ms
The Gson version is much faster than the "Serialization" one. Why?!
Is there anything wrong is my test code, or Java built-in serialization is actually slow?