英文:
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 = "a"+"b"+"c";
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 <String "abc"> [16]
2 astore_1 [string]
So the following would be unnecessary overhead.
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("a");
sBuilder.append("b");
sBuilder.append("c");
However, if you ever need to call append on the same StringBuilder
object you can do the following:
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("a").append("b").append("c");
StringBuilder.append
returns its own instance.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论