javastringstring-concatenationstringwriter

Is there anything (any way) to concatenate java Strings faster than StringWriter?


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.


Solution

  • 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.