1

I am pulling a bunch of simple data and constructing a big (1kB - 2kB) String. I'm new to this language, but after reading, this seems likely the fastest (i.e. least amount of copying):

String tmpTable = "<table border=\"1\">" + System.lineSeparator();
StringWriter stringWriter = new StringWriter(1024);
String tr = "";

stringWriter.append(tmpTable);
for(Project p:projectSet) {
  tr = String.format(trFmt, p.getId(), p.getTitle(),
    p.getPriority(), p.getStatus());
  stringWriter.append(tr);
}
stringWriter.append("</table>" + System.lineSeparator());
stringWriter.flush();
stringWriter.close(); // old habits

Is there a "better" way?

If it were 'C', I might be inclined to use a "char *argv[]" sort of deal.

Boann
  • 48,794
  • 16
  • 117
  • 146
Erik Bennett
  • 1,049
  • 6
  • 15
  • There are possibly XSS vulnerabilities in your code, depending on what `p.getTitle()`, `p.getStatus()` return. Make sure you're escaping any `< > " ' &` characters in text before writing it to HTML. – Boann Oct 09 '14 at 04:35

2 Answers2

3

StringBuilder is standard to use. It has the initial buffer size constructor and the append methods that you are looking for. To get the value out of it, call toString() on the builder. There is no way (need) to close() or flush() it.

nmore
  • 2,474
  • 1
  • 14
  • 21
2

Is there a better way?

Yes, I believe there is a better way.

You appear to be constructing HTML in memory into a large String. I suggest you don't do that.

I believe you should be streaming the data to the client (Buffered) OutputStream. Obviously if you need some formatting (or to load a String from resource bundle by locale) you can perform that limited computation (and maybe later optimize that with a cache) but then resume streaming. Adding additional String buffers (in my experience) harms performance.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • I see what you mean. If I did this once per HTTP request, it would be a wreck. I was unclear about my intentions, though the clever people out there picked up on the HTML and provided valuable feedback. I'm writing to a static page on a disk. This will be my "cache". I expect to only "compile" these pages, not once per request, but rather once per hour. – Erik Bennett Oct 09 '14 at 15:23