当它被声明为 String Builder vs string

huangapple go评论82阅读模式
英文:

When it is Declared String Builder vs string

问题

当你像这样解析时,实例是否会被创建?

String string = "a" + "b" + "c";

是否应该像以下方式声明?

StringBuilder sBuilder = new StringBuilder();
sBuilder.append("a");
sBuilder.append("b");
sBuilder.append("c");
英文:

When you decere like this . Are the instances created?

String string = "a"+"b"+"c";

Should it be declared like following?

StringBuilder sBuilder = new StringBuilder();
sBuilder.append("a");
sBuilder.append("b");
sBuilder.append("c");

答案1

得分: 1

对于

String string = "a"+"b"+"c";

编译器生成了一个完整的字符串。字节码如下所示。由于它正在处理常量,大多数编译器会以这种方式执行。根据JDK版本的不同,变量的拼接可能会有所不同。

0 ldc <String "abc"> [16]
2 astore_1 [string]

因此,以下内容将是不必要的开销。

StringBuilder sBuilder = new StringBuilder();
sBuilder.append("a");
sBuilder.append("b");
sBuilder.append("c");

但是,如果您需要在同一个 `StringBuilder` 对象上调用 append,可以使用以下方法:

StringBuilder sBuilder = new StringBuilder();
sBuilder.append("a").append("b").append("c");

`StringBuilder.append` 返回自己的实例。
英文:

For

String string = &quot;a&quot;+&quot;b&quot;+&quot;c&quot;;

The compiler generates a complete string. The bytecode looks like
this. Most compilers would do it this way since it is working with constants. Variable concatenation may be handled differently depending on the version of the JDK.

  0  ldc &lt;String &quot;abc&quot;&gt; [16]
  2  astore_1 [string]

So the following would be unnecessary overhead.

StringBuilder sBuilder = new StringBuilder();
sBuilder.append(&quot;a&quot;);
sBuilder.append(&quot;b&quot;);
sBuilder.append(&quot;c&quot;);

However, if you ever need to call append on the same StringBuilder object you can do the following:

StringBuilder sBuilder = new StringBuilder();
sBuilder.append(&quot;a&quot;).append(&quot;b&quot;).append(&quot;c&quot;);

StringBuilder.append returns its own instance.

huangapple
  • 本文由 发表于 2020年8月7日 09:25:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63293920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定