Code Pretty Print Script

Wednesday, November 6, 2013

Avoid Intermediate (Deep) Copies

The following code is provided for example purposes only!
For your enjoyment, three approaches to a singular problem; serializing a JSONObject to a Web client.

javax.servlet.http.HttpServletResponse response = <...>
java.io.PrintWriter pw = response.getWriter();
try {
    org.json.JSONObject json = <...>
    StringBuffer sb = new StringBuffer();
    sb.append(json.toString());
    pw.print(sb.toString());
} finally {
    pw.flush();
}

The problem isn't limited to stringify'ing a copy of the json object and writing it to the StringBuffer (which you probably shouldn't be using anyway). The best approach isn't just
javax.servlet.http.HttpServletResponse response = <...>
java.io.PrintWriter pw = response.getWriter();
try {
    org.json.JSONObject json = <...>
    pw.print(json.toString());
} finally {
    pw.flush();
}

Although that is clearly an improvement. Rather, it's best to allow the JSONObject to write itself (instead of creating "deep" copies)!
javax.servlet.http.HttpServletResponse response = <...>
java.io.PrintWriter pw = response.getWriter();
try {
    org.json.JSONObject json = <...>
    json.write(pw);
} finally {
    pw.flush();
}