Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to StringWriter but with StringBuilder internally in Java?

I've noticed that StringWriter uses internally a StringBuffer. But if you don't need that synchronisation overhead is there an equivalent to StringWriter that uses a StringBuilder inside?

like image 547
sa_vedem Avatar asked Jul 25 '14 11:07

sa_vedem


2 Answers

If you happen to use Apache Commons IO, then you can re-use StringBuilderWriter which is described as follows:

Writer implementation that outputs to a StringBuilder.

NOTE: This implementation, as an alternative to java.io.StringWriter, provides an un-synchronized (i.e. for use in a single thread) implementation for better performance. For safe usage with multiple Threads then java.io.StringWriter should be used.

Its implementation is also straightforward as expected, so you can pattern from it and implement it yourself without adding a new dependency.

like image 155
Kenston Choi Avatar answered Oct 12 '22 22:10

Kenston Choi


No, there is no equivalent that uses a StringBuilder in the current standard java API (at least 7, I didn't investigate on 8).

Should the rationale behind your question be the performances, I don't think you have to worry. But should this aspect be critical, you can implement a StringWriter class on your own but using a StringBuilder to check whether the difference is significant. If yes, keep your own, and otherwise, there's no issue.

like image 41
Shlublu Avatar answered Oct 13 '22 00:10

Shlublu