so I am building an html table using a list of object arrays, but its going very unacceptably slow. any way to optimize it?
public String generateHtmlTable(List<Object[]> resultSet) {
totalRows = resultSet.size();
StringBuilder sb = new StringBuilder();
sb.append("<table width=\"900px\">");
sb.append("<tr>");
sb.append("<th width=\"10%\" align=\"left\"><b>col1</b></th>");
sb.append("<th width=\"25%\" align=\"left\"><b>col2</b></th>");
sb.append("<th width=\"20%\" align=\"left\"><b>col3</b></th>");
sb.append("<th width=\"15%\" align=\"left\"><b>col4</b></th>");
sb.append("<th width=\"10%\" align=\"left\"><b>col5</b></th>");
sb.append("<th width=\"10%\" align=\"left\"><b>col6</b></th>");
sb.append("<th width=\"10%\" align=\"left\"><b>col7</b></th>");
sb.append("<th width=\"5%\" align=\"left\"><b>col8</b></th>");
sb.append("<th width=\"5%\" align=\"left\"><b>col9</b></th>");
sb.append("</tr>");
for (Object[] row : resultSet) {
sb.append("<tr>");
for (Object cell : row) {
sb.append("<td>");
sb.append(((cell != null) ? cell.toString() : ""));
sb.append("</td>");
}
sb.append("</tr>");
rowsProcessed += 1;
}
sb.append("</table>");
return sb.toString();
}
1 Answer 1
You are building the result html in memory before (presumably) streaming it out in your response from some web server. You can avoid buffering like this by writing straight to the response output stream. This has two advantages: 1) you are not creating a copy of your response in memory before returning it. 2) you are returning bytes before you have scrolled through all the results from your database. So both cut down on response time.
Most serialization frameworks on top of e.g. jax.rs would do this for you or you can plug in your own custom serialization. Alternatively if you are using some kind of servlet app, you can just get a writer straight from the response object.
resultSet
. Run your code with the profiler to see what really takes the most of processing time.append()
. Something likesb.append("<th>...</th>" + "<th> ... </th>" + "<th> ... </th>");
Is that going to help? You would have to try, I guess. Even better would be to omit the+
operator as well, if possible.+
. But if your code allows, you could try to omit that entirely and just append all cells in one call. That might help.try is constructing the
StringBuilder with a given capacity, so it doesn't need to copy the internal data more often then it need to.