在Java中,String.format()的实现中是否考虑了字符串的不可变性?
由于 Java 中的字符串是不可变的,因此我总是使用 StringBuilder 或 StringBuffer 来连接字符串。 String.format() 方法是否可以像 StringBuilder 或 StringBuffer 一样处理这个问题?换句话说,String.format() 是否像 StringBuffer 或 StringBuilder 一样管理内存?
Since Strings in Java are immutable, I've always used StringBuilder or StringBuffer to concatenate Strings. Does the String.format() method handle this issue as well as StringBuilder or StringBuffer? In other words, does String.format() manage memory as well as StringBuffer or StringBuilder?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 Oracle JDK 的源代码,该实现似乎为每个
String#format
调用创建一个新的Formatter
,而该调用又分配一个新的StringBuilder
每次调用的代码>。所以是的。但正如对您的问题的评论所提到的,这在很大程度上是特定于实现的,尽管常识表明它将选择最有效的做事方式。Based on the source code of Oracle JDK, it seems that the implementation creates a new
Formatter
for eachString#format
call which in turn allocates a freshStringBuilder
for each call. So yes. But as mentioned by the comment to your question, this is very much implementation specific though common sense entails that it would choose the most efficient way of doing things.