Well, since the answers seem to emphasize the stylistic reasons for each other's preferences, I decided to generalize the time test.
Change Following the robinst observation above, I now have three methods: one that adds the PrintWriter (StringWriter) style, and two that use StringBuilder: one with the addition of a new line inside the add (as in the original: builder.append(thing + newline); ), and the other is a separate application (as described above: builder.append(thing).append(newline); ).
I followed my usual benchmarking scheme: first, call several methods (1000 in this case) to give the optimizer time to warm up, and then call them many times (100 000 in this case) in an alternating sequence, so that any changes to the workstation runtime are more fairly distributed and run the test itself several times and average the results.
Oh, and, of course, the number of lines created and the length of the lines are randomized, but they should be the same for each pair of calls, because I wanted to avoid any possible effects of the buffer size or line size on the results.
The code for this is here: http://pastebin.com/vtZFzuds
Note. I have not updated the pastebin code yet to reflect the new test.
TL, DR? The average results for 100,000 calls for each method are pretty close:
- 0.11908 ms per call using StringBuilder (+ new line inside the patent)
- 0.10201 ms per call using StringBuilder (new line as a separate addition)
- 0.10803 ms per call using PrintWriter (StringWriter)
It is so close that time almost does not matter to me, so I will continue to do what I always did: StringBuilder (with a separate addition) for stylistic reasons. Of course, while working in this established and mature codebase, I basically adhere to existing conventions in order to minimize surprise.
CPerkins Jun 05 '10 at 16:34 2010-06-05 16:34
source share