Search code examples
javaperformanceio

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?


Solution

  • 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.