stringbuilder 调用中的 Java 字符串连接
据我所知,StringBuilder 在连接期间不在字符串池中创建临时字符串实例,从而有助于减少内存使用量。 但是,如果我这样做会发生什么:
StringBuilder sb = new StringBuilder("bu");
sb.append("b"+"u");
它会编译成吗
sb.append("b");
sb.append("u");
?或者它取决于优化标志?或者我失去了弦乐建造者的全部好处? 或者这个问题没有意义? :)
As far as I know, StringBuilder helps to reduce memory usage by not creating temporary string instances in the string pool during concats.
But, what happens if I do sth like this:
StringBuilder sb = new StringBuilder("bu");
sb.append("b"+"u");
Does it compile into
sb.append("b");
sb.append("u");
? Or it depends on optimalization flags? Or I loose the whole benefit if stringbuilders?
Or this quetion makes no sense? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,
"b" + "u"
将创建一个不可变的b
字符串、一个不可变的u
字符串,然后创建第三个不可变的 < code>bu 传递到StringBuilder
实例的字符串。No, the
"b" + "u"
will create an immutableb
string, an immutableu
string, and then create a third immutablebu
string that gets passed into theStringBuilder
instance.错误:
正确:
最佳://因为你已经知道里面会有什么了! ;)
:)
编辑
我想我上面的答案在仅处理文字时是不正确的...
:/
WRONG:
CORRECT:
BEST: //Since you knew what's going to be in there already! ;)
:)
EDIT
I guess my answer above is not correct when dealing with literals only...
:/
它编译为 sb.append("bu"),因为编译器将多个字符串文字的串联转换为单个字符串文字。
如果你有
它,会将其编译为
So 在这种情况下你应该更喜欢
。
It compiles to
sb.append("bu")
, because the compiler translates the concatenation of multiple String litterals to a single String litteral.If you had
it would compile it to
So you should prefer
in this case.
由于
"b" + "u"
是一个在编译时计算的表达式,因此它会像"bu"
一样被编译。另一方面,如果您有两个字符串变量,则此优化不会启动:
以下代码片段...
...被编译为:
即类似于
您在第 17-21 行中看到的一个额外的
StringBuilder
是为了连接a
和b
而创建的。然后,在第 32 行获取此临时StringBuilder
的结果String
,并将其附加到第 35 行的原始StringBuilder
。(字节码是由JDK 中的
javap
命令试试吧,非常简单!)Since
"b" + "u"
is an expression which is evaluated at compile time, it will be compiled just as if you had"bu"
.If you on the other hand had two string variables, this optimization wouldn't kick in:
The following snippet...
...gets compiled as:
I.e. something similar to
As you can see in line 17-21 an extra
StringBuilder
is created for the purpose of concatenatinga
andb
. The resultingString
of this temporaryStringBuilder
is then fetched on line 32 and appended to the originalStringBuilder
on line 35.(The bytecode was generated by the
javap
command which is part of the JDK. Try it out, it's really simple!)