I created a Java Servlet that get query result from mySQL database and print it in XML format.
the problem is that it takes a very long time, something about three minutes to print the xml result while in my PHP script it takes 5 seconds.
My Servlet relevant function is:
( run a query and return the xml in a String variable, then, print it to the page )
public String QueryResult(String query)
{
String retStr;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection ("jdbc:mysql://"+this.host+":"+this.port+"/"+this.db, this.user, this.pass);
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery(query);
ResultSetMetaData rsMetaData = rset.getMetaData();
retStr = "<Result>\n";
while (rset.next())
{
retStr += "\t<Item>\n";
for (int i=1;i<=rsMetaData.getColumnCount();i++)
{
retStr += "\t\t<"+rsMetaData.getColumnName(i)+">"+ rset.getString(i) + "</"+rsMetaData.getColumnName(i)+">\n";
}
retStr += "\t</Item>\n";
}
retStr += "</Result>\n";
stmt.close();
conn.close();
}
catch(Exception e)
{
return "<Result><Error>"+e.toString()+"</Error></Result>";
}
return retStr;
}
String Concatenation:
First of all, when speed matters, you do not want to concatenate strings the way you do. Each time you concatenate a
Stringyou are creating a new one.Better use
StringBuilderwith a well planned capacity, as the default one won’t probably suit your need judging from the code snippet you show.Also See:
String, StringBuffer, and StringBuilder
Why to use StringBuffer in Java instead of the string concatenation operator
XML:
Might not be related to your performance issue but might come in handy: XStream
“Performance” does figure in their features list.