String assembly by StringBuilder vs StringWriter and PrintWriter

I recently came across an idiom that I had not seen before: string assembly by StringWriter and PrintWriter. I mean, I know how to use them, but I always used StringBuilder. Is there a specific reason for preferring one over the other? The StringBuilder method seems more natural to me, but is it just a style?

I examined a few questions here (including the one closest: StringWriter or StringBuilder ), but not one in which the answers actually address the question of whether there is a reason to prefer one after the other for simple string assembly.

This is an idiom I've seen and used many times: a string assembly by StringBuilder:

public static String newline = System.getProperty("line.separator"); public String viaStringBuilder () { StringBuilder builder = new StringBuilder(); builder.append("first thing").append(newline); // NOTE: avoid doing builder.append("first thing" + newline); builder.append("second thing").append(newline); // ... several things builder.append("last thing").append(newline); return builder.toString(); } 

And this is a new idiom: string assembly by StringWriter and PrintWriter:

 public String viaWriters() { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); printWriter.println("first thing"); printWriter.println("second thing"); // ... several things printWriter.println("last thing"); printWriter.flush(); printWriter.close(); return stringWriter.toString(); } 

Edit It seems that there is no specific reason to prefer each other, so I accepted the answer that best fits my understanding, and + 1 all the other answers. In addition, I sent my answer, presenting the results of the comparative test that I performed, in response to one of the answers. Thanks to everyone.

Edit again It turns out there is a specific reason to prefer one (in particular StringBuilder) over the other. What I missed for the first time was adding a new line. When you add a new line (as mentioned above, as a separate supplement), it is a little faster - not very, but in combination with clarity of intent, it is definitely better. See my answer below for better timings.

+46
java
Jun 05 '10 at 2:51 p.m.
source share
6 answers

Stylistically, StringBuilder approach is cleaner. This is less than lines of code and uses a class specifically designed to create lines.

Another consideration is more effective. A better way to answer this question would be to compare the two alternatives. But there are some clear pointers that StringBuilder should be faster. To start, StringWriter uses a StringBuilder StringBuffer under the hood to store characters written to the stream.

+16
Jun 05 '10 at 15:03
source share

StringWriter is what you use when you want to write to a string, but you are working with the API that Writer or Stream expects. This is not an alternative; it is a compromise: you use StringWriter only when you need to.

+33
Jun 05 2018-10-06T00:
source share

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.

+18
Jun 05 '10 at 16:34
source share

Writers - PrintWriter writes to the stream. These are strange things like suppressing IOExceptions. System.out is one of them. - StringWriter is a Writer that writes to a StringBuffer (similar to ByteArrayOutputStream for OutputStreams)

StringBuilder - and of course StringBuilder - this is what you need if you just want to build strings in memory.

Conclusion

Design writers are designed to push personal data out of the stream (usually to a file or through a connection), so the ability to use Writers to easily assemble strings seems like a bit of a side effect.

StringBuilder (and its synchronized sibling StringBuffer) are designed to build strings (read strings). If you look at the StringBuilder API , you can see that you can only add vanilla, but also replace, reverse, insert, etc. StringBuilder is your string construction friend.

+12
Jun 05 '10 at 14:55
source share

I see two advantages of the PrintWriter method: (1) You do not need to add a β€œ+ new line” at the end of each individual line, which actually leads to code reduction if you need to write a lot. (2) You do not need to call System.getProperty (); you let PrintWriter worry about what should be a newline.

+7
Oct 20 '10 at 19:51
source share

in this link: http://nohack.eingenetzt.com/java/java-stringwriter-vs-stringbuilder the author shows that StringWriter is even a little faster than StringBuilder.and also said: "Therefore, when large amounts of data come into play, StringWriter clearly shows its superior performance over StringBuilder. "

+1
Sep 17 '14 at 10:56 on
source share



All Articles