Which runs faster: using OutputStreamWriter.write() for each string to be written, or using StringBuilder to create one large string, then using write() once? Please explain why.
Here’s using write() many times:
writer.write("Registered Players:\n");
while (it.hasNext()) {
int playerID = (Integer) it.next();
Player player = playerRegistry.get(playerID);
writer.write(playerID+": "+player.getPlayerName()+"\n");
}
And here’s with StringBuilder:
builder.append("Registered Players:\n");
while (it.hasNext()) {
int playerID = (Integer) it.next();
Player player = playerRegistry.get(playerID);
builder.append(playerID+": "+player.getPlayerName()+"\n");
}
writer.write(builder.toString());
It all depends on which kind of
OutputStreamyou’re writing to.If it’s writing to memory (
ByteArrayOutputStream), it won’t make any difference.If you’re writing to a
BufferedOutputStream, the stream will buffer your lines in memory and write the buffer once it’s full to the underlying stream, so it won’t make any difference either.If you’re writing to a
FileOutputStreamor aSocketOutputStream, buffering will lead to better performance. But buffering everything into memory could be a bad idea if the data to write is too big: it could need too much memory.The best thing to do is to use a buffered writer or stream, which will take care of buffering for you, transparently, and thus avoid too many low-level writes without having to buffer explicitely into a
StringBuilder.