I was having a play around with converting JSON strings to and from POJOs. And I wondered whether it would be best have a new class definition for different types of json. As I assumed that having google gson having to parse null fields would slow it down.(not noticeably, but still. I thought it was worth the experiment and post here.) For example logging a client in might be.
public class CustomJSON {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
But I could have other things to recieve from the client such as. favourite color, food ect.
public class CommonJSON {
private String name;
private String food;
private String music;
//getters and setters.
}
So I ran the test.
CustomJson is the same as above and with CommonJSON I added 50 other null fields that would be unused a to ax.
public class CommonJSON {
private String name;
private String a;
...
private String ax;
//getters and setters.
}
My main method for running the test is as follows.
public static void main(String[] args) {
// TODO Auto-generated method stub
String theJSON = "";
int passes = 100;
long start;
long finish;
long exeTime;
Gson gson = new Gson();
//custom JSON
start = System.nanoTime();
for(int i=0;i<passes;i++)
{
CustomJSON custom = new CustomJSON();
custom.setName("StackOverFlow");
theJSON = gson.toJson(custom);
}
finish = System.nanoTime();
System.out.println(theJSON);
exeTime = finish-start;
System.out.println("Custom JSON \n\t>\t "+(exeTime)+" Nano seconds");
System.out.println(" \t>\t "+Math.round((exeTime)/1000000.0)+" Micro seconds\n");
//common JSON
start= System.nanoTime();
for(int i=0;i<passes;i++)
{
CommonJSON toClientJSONd = new CommonJSON();
toClientJSONd.setName("StackOverFlow");
theJSON = gson.toJson(toClientJSONd);
}
finish = System.nanoTime();
System.out.println(theJSON);
exeTime = finish-start;
System.out.println("Common JSON \n\t>\t "+(exeTime)+" Nano seconds");
System.out.println(" \t>\t "+Math.round((exeTime)/1000000.0)+" Micro seconds");
}
The results are not as I expected. With 100 passes the common class finishes 10ms faster on my machine. If I increase the number of passes the common class eventually starts to lag behind.
What makes the common class faster to start of with? Should I worry about this in my code or just use one class for a common class for all jsons?
I can provide full source and an eclipse project if anyone would like to run it.