First I would suggest using JProfiler or JConsole, both included in JDK6, to pinpoint exactly where the performance hit is.
Without knowing where the CPU usage is, I would avoid synchronized
. I doubt append
is the problem. Clean it up by getting rid of the static
local jsonVal
, too.
public static String toJson(final List<QuotesData> quotesData) {
final List<QuotesData> theData = new ArrayList<QuotesData>(quotesData);
StringBuffer jsonVal = new StringBuffer();
jsonVal.append("{");
for (QuotesData quote : quotesData) {
jsonVal.append("\"").append(quote.getSymbol()).append("\":[{");
jsonVal.append("\"ask\":\"").append(quote.getAsk()).append(
"\",");
jsonVal.append("\"bid\":\"").append(quote.getBid()).append(
"\",");
jsonVal.append("\"time\":\"").append(quote.getDateTime())
.append("\"}],");
}
jsonVal.append("}");
String returnString = jsonVal.toString();
return returnString.toString().replace("}],}", "}]}");
}
Consider using a JSON library like Gson. The code becomes much simpler. You can tweak the output if needed:
private static final Gson gson = new Gson();
public static String toJson(final List<QuotesData> quotesData) {
return gson.toJson(new ArrayList<QuoteData>(quotesData));
}