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

醉酒当歌 提交于 2020-01-24 04:11:09

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/24955072/is-there-an-equivalent-to-stringwriter-but-with-stringbuilder-internally-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!