In the code below, which case (1 or 2) is more “efficient”?
static final String NEWLINE = System.getProperty("line.separator");
Vector<String> text_vec = ...;
FileWriter file_writer = new FileWriter(path);
BufferedWriter buffered_writer = new BufferedWriter(file_writer);
try {
for (String text: text_vec) {
// Case 1: String concatenation
buffered_writer.write(text + NEWLINE);
// Case 2: Extra call to write()
buffered_writer.write(text);
buffered_writer.write(NEWLINE);
}
}
finally {
buffered_writer.close();
}
In case #1, as I understand, the String concatenation is handled by the Java compiler by automatically allocating a StringBuilder object. Since the String values are not known at compile time, it is not possible to concatenate “early” (during compile time).
So the question stands: Which one is more efficient (CPU/memory/wall clock time)?
I am leaving the exact definition of “efficient” to those whom answer. I am not an expert on the Java virtual machine.
Unless you benchmark it and prove that you have a good reason not to, you should write directly to the buffer. It’s there to provide an efficient method for writing to a file.
Also, don’t forget to flush the buffer when you’re done writing to it.