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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With