在StringBuffer中追加或+运算符?

Gur*_*lki 4 java string

在我的项目中有一些使用StringBuffer对象的代码片段,其中一小部分如下

StringBuffer str = new StringBuffer();

str.append("new " + "String()");
Run Code Online (Sandbox Code Playgroud)

所以我对使用append方法和+运算符感到困惑.

即以下代码可以写为

str.append("new ").append("String()");
Run Code Online (Sandbox Code Playgroud)

那么两条线路是否相同?(功能上是,但是)或者是否有任何特殊用途?即性能或可读性或???

谢谢.

Jon*_*eet 15

这种情况下,使用第一种形式更有效 - 因为编译器会将其转换为:

StringBuffer str = new StringBuffer();
str.append("new String()");
Run Code Online (Sandbox Code Playgroud)

因为它连接了常量.

还有一些更普遍的观点:

  • 如果这些表达式中的任何一个不是常量,那么在两次调用时你会更好(性能方面)append,以避免无缘无故地创建一个中间字符串
  • 如果您使用的是最新版本的Java,StringBuilder则通常是首选
  • 如果你要立即附加一个字符串(并且你知道它在构造时是什么),你可以将它传递给构造函数


nre*_*nre 6

实际上,字节码编译器将替换所有涉及调用的Java程序中非常量的字符串连接StringBuffer.那是

int userCount = 2;
System.out.println("You are the " + userCount + " user");
Run Code Online (Sandbox Code Playgroud)

将被改写为

int userCount = 2;
System.out.println(new StringBuffer().append("You are the ").append(userCount).append(" user").toString());
Run Code Online (Sandbox Code Playgroud)

这至少是在反编译用JDK 5或6编译的java类文件时可观察到的内容.请参阅此文章.